java.util.Optional
原文链接
文章目录
- 1、Optional作用
- 2、常用API
- 构造相关
- get / orElse / orElseGet / orElseThrow
- isPresent / ifPresent
- filter
- map / flatMap
- 3、源码翻译
1、Optional作用
- 类位于:java.util.Optional
- 臭名昭著的空指针异常是导致Java应用程序失败的最常见原因;以前为了解决空指针异常,Google公司著名的Guava项目引入了Optional类,Guava通过使用检查空值的方式来防止代码污染,它鼓励程序员写更干净的代码;受到Google Guava的启发Optional类已经成为Java 8类库的一部分
- Optional实际上是个容器,它可以保存类型T的值,或者仅仅保存null,Optional提供很多有用的方法,这样我们就不用显式进行空值检测
- JDK8在线源码英文文档:https://nowjava.com/readcode/jdk8
- JDK8在线源码中文文档:https://www.matools.com/api/java8
2、常用API
构造相关
// 空值实例Optional<Object> empty = Optional.empty();// 非空值实例Optional<String> nonEmpty = Optional.of("123");// 可空值实例Optional<Object> maybeEmpty = Optional.ofNullable(null);
get / orElse / orElseGet / orElseThrow
Optional<Object> empty = Optional.empty();// get方法遇到空值会抛出异常NoSuchElementExceptionObject o = empty.get();// 如果存在,则返回值,否则返回传入的默认值Object orElse = empty.orElse("123");System.out.println(orElse);//123// 如果存在,则返回该值,否则返回 Supplier.get()的返回值Object orElseGet = empty.orElseGet(new Supplier<Object>() {@Overridepublic Object get() {return "abc";}});System.out.println(orElseGet);//abctry {// 如果存在,返回该值,否则抛出异常(此异常是Supplier.get()返回的)Object o = empty.orElseThrow(new Supplier<Throwable>() {@Overridepublic Throwable get() {return new NullPointerException();}});} catch (Throwable e) {throw new RuntimeException(e);}
isPresent / ifPresent
// 判断值是否存在System.out.println(empty.isPresent());// false// 有值才会执行accept方法empty.ifPresent(new Consumer<Object>() {@Overridepublic void accept(Object o) {//System.out.println(o.hashCode());}});
filter
Optional<String> s = Optional.of("11");// 如果存在值,并且该值与Predicate.test()匹配,则返回描述该值的Optional,否则返回空值的OptionalOptional<String> s1 = s.filter(new Predicate<String>() {@Overridepublic boolean test(String s) {return false;}});System.out.println(s1);// Optional.empty
map / flatMap
- map:apply返回的是Optional包装的值
- flatMap:apply方法返回是Optional
// map处理Optional<Object> optiona4 = Optional.ofNullable("abc");Optional<Object> o4 = optiona4.map(new Function<Object, Object>() {@Overridepublic Object apply(Object o) {System.out.println(o);//abcreturn "123";}});System.out.println(o4.get());//123// flatMap处理Optional<Object> optiona5 = Optional.ofNullable("efg");Optional<String> optiona6 = optiona5.flatMap(new Function<Object, Optional<String>>() {@Overridepublic Optional<String> apply(Object o) {System.out.println(o);//efgreturn Optional.of("456");}});System.out.println(optiona6.get());//456
3、源码翻译
package java.util;import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;/*** A container object which may or may not contain a non-null value.* 一个可能包含也可能不包含非null值的容器对象* If a value is present, {@code isPresent()} will return {@code true} and* {@code get()} will return the value.* 如果存在值,isPresent()将返回 true,get()将返回该值。** <p>Additional methods that depend on the presence or absence of a contained* value are provided, such as {@link #orElse(Object) orElse()}* (return a default value if value not present) and* {@link #ifPresent(Consumer) ifPresent()} (execute a block* of code if the value is present).* 还提供了依赖于包含值是否存在的其他方法,例如 orElse(Object) orElse()(如果值不存在,则返回默认值)* 和 ifPresent(Consumer) ifPresent()(如果值存在,则执行代码块)。** <p>This is a <a href="../lang/doc-files/ValueBased.html">value-based</a>* class; use of identity-sensitive operations (including reference equality* ({@code ==}), identity hash code, or synchronization) on instances of* {@code Optional} may have unpredictable results and should be avoided.** 这是一个 value-based 的类;* 在Optional实例上的身份敏感操作(包括引用相等性==、标识哈希代码或同步)可能会产生不可预知的结果,应避免使用。** @since 1.8*/
public final class Optional<T> {/*** Common instance for {@code empty()}.* empty()的常见实例*/private static final Optional<?> EMPTY = new Optional<>();/*** If non-null, the value; if null, indicates no value is present* 如果非空,则为值;如果为 null,则表示不存在任何值*/private final T value;/*** Constructs an empty instance.* 构造一个空实例** @implNote Generally only one empty instance, {@link Optional#EMPTY},* should exist per VM.* 通常,每个 VM 只能存在一个空实例*/private Optional() {this.value = null;}/*** Returns an empty {@code Optional} instance. No value is present for this* Optional.* 返回一个空的Optional实例。此Optional不存在任何值。** @apiNote Though it may be tempting to do so, avoid testing if an object* is empty by comparing with {@code ==} against instances returned by* {@code Option.empty()}. There is no guarantee that it is a singleton.* Instead, use {@link #isPresent()}.* todo 此处解释不是太明白,比较对象为空? 确保单例?* 尽管这样做可能很诱人,但请避免通过 == 与 Option.empty() 返回的实例来比较测试对象是否为空。* 不能保证它是单例。相反,请使用 isPresent()** @param <T> Type of the non-existent value* @return an empty {@code Optional}*/public static<T> Optional<T> empty() {@SuppressWarnings("unchecked")Optional<T> t = (Optional<T>) EMPTY;return t;}/*** Constructs an instance with the value present.* 构造一个有值的实例** @param value the non-null value to be present* @throws NullPointerException if value is null*/private Optional(T value) {this.value = Objects.requireNonNull(value);}/*** Returns an {@code Optional} with the specified present non-null value.** 返回具有指定的非空值的 Optional实例** @param <T> the class of the value* @param value the value to be present, which must be non-null 必须非空* @return an {@code Optional} with the value present* @throws NullPointerException if value is null*/public static <T> Optional<T> of(T value) {return new Optional<>(value);}/*** Returns an {@code Optional} describing the specified value, if non-null,* otherwise returns an empty {@code Optional}.* 返回描述指定值的 Optional实例,如果非 null,则返回空的Optional实例** @param <T> the class of the value* @param value the possibly-null value to describe 要描述的可能为空值* @return an {@code Optional} with a present value if the specified value* is non-null, otherwise an empty {@code Optional}*/public static <T> Optional<T> ofNullable(T value) {return value == null ? empty() : of(value);}/*** If a value is present in this {@code Optional}, returns the value,* otherwise throws {@code NoSuchElementException}.* 如果Optional里面有值,则返回该值,否则抛出异常NoSuchElementException** @return the non-null value held by this {@code Optional}* @throws NoSuchElementException if there is no value present** @see Optional#isPresent()*/public T get() {if (value == null) {throw new NoSuchElementException("No value present");}return value;}/*** Return {@code true} if there is a value present, otherwise {@code false}.* 如果存在值,则返回 true,否则返回 false** @return {@code true} if there is a value present, otherwise {@code false}*/public boolean isPresent() {return value != null;}/*** If a value is present, invoke the specified consumer with the value,* otherwise do nothing.* 如果存在值,则使用该值调用指定的使用者,否则不执行任何操作** @param consumer block to be executed if a value is present* @throws NullPointerException if value is present and {@code consumer} is* null 如果值存在且consumer为空 就会抛出异常*/public void ifPresent(Consumer<? super T> consumer) {if (value != null)consumer.accept(value);}/*** If a value is present, and the value matches the given predicate,* return an {@code Optional} describing the value, otherwise return an* empty {@code Optional}.* 如果存在值,并且该值与Predicate.test()匹配,则返回描述该值的Optional,否则返回空值的Optional** @param predicate a predicate to apply to the value, if present* @return an {@code Optional} describing the value of this {@code Optional}* if a value is present and the value matches the given predicate,* otherwise an empty {@code Optional}* @throws NullPointerException if the predicate is null*/public Optional<T> filter(Predicate<? super T> predicate) {Objects.requireNonNull(predicate);if (!isPresent())return this;elsereturn predicate.test(value) ? this : empty();}/*** If a value is present, apply the provided mapping function to it,* and if the result is non-null, return an {@code Optional} describing the* result. Otherwise return an empty {@code Optional}.* 如果存在值,则对其应用提供的映射函数,如果结果为非 null,则返回描述结果的 {@code Optional}。* 否则不存在值,返回空值的Optional** @apiNote This method supports post-processing on optional values, without* the need to explicitly check for a return status. For example, the* following code traverses a stream of file names, selects one that has* not yet been processed, and then opens that file, returning an* {@code Optional<FileInputStream>}:* 此方法支持对可选值进行后处理,而无需显式检查返回状态。* 例如,以下代码遍历文件名流,选择尚未处理的文件名流,然后打开该文件,返回Optional<FileInputStream>** <pre>{@code* Optional<FileInputStream> fis =* names.stream().filter(name -> !isProcessedYet(name))* .findFirst()* .map(name -> new FileInputStream(name));* }</pre>** Here, {@code findFirst} returns an {@code Optional<String>}, and then* {@code map} returns an {@code Optional<FileInputStream>} for the desired* file if one exists.* 在这里,findFirst返回一个Optional<String>,然后map返回所需文件的Optional<FileInputStream>(如果存在)。** @param <U> The type of the result of the mapping function* @param mapper a mapping function to apply to the value, if present* @return an {@code Optional} describing the result of applying a mapping* function to the value of this {@code Optional}, if a value is present,* otherwise an empty {@code Optional}* @throws NullPointerException if the mapping function is null*/public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {Objects.requireNonNull(mapper);if (!isPresent())return empty();else {return Optional.ofNullable(mapper.apply(value));}}/*** If a value is present, apply the provided {@code Optional}-bearing* mapping function to it, return that result, otherwise return an empty* {@code Optional}. This method is similar to {@link #map(Function)},* but the provided mapper is one whose result is already an {@code Optional},* and if invoked, {@code flatMap} does not wrap it with an additional* {@code Optional}.** 如果存在值,请对其应用提供的 {@code 可选} 轴承映射函数,返回该结果,否则返回空的 {@code 可选}。** 此方法类似于map,但提供的映射器的结果已经是 Optional,如果调用flatMap会用额外的Optional包装它。** @param <U> The type parameter to the {@code Optional} returned by* @param mapper a mapping function to apply to the value, if present* the mapping function* @return the result of applying an {@code Optional}-bearing mapping* function to the value of this {@code Optional}, if a value is present,* otherwise an empty {@code Optional}* @throws NullPointerException if the mapping function is null or returns* a null result*/public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {Objects.requireNonNull(mapper);if (!isPresent())return empty();else {return Objects.requireNonNull(mapper.apply(value));}}/*** Return the value if present, otherwise return {@code other}.* 如果存在,则返回值,否则返回入参other** @param other the value to be returned if there is no value present, may* be null* @return the value, if present, otherwise {@code other}*/public T orElse(T other) {return value != null ? value : other;}/*** Return the value if present, otherwise invoke {@code other} and return* the result of that invocation.* 如果存在,则返回该值,否则返回 Supplier.get()的返回值** @param other a {@code Supplier} whose result is returned if no value* is present* @return the value if present otherwise the result of {@code other.get()}* @throws NullPointerException if value is not present and {@code other} is* null*/public T orElseGet(Supplier<? extends T> other) {return value != null ? value : other.get();}/*** Return the contained value, if present, otherwise throw an exception* to be created by the provided supplier.* 如果存在,返回该值,否则抛出异常(此异常是Supplier.get()返回的)** @apiNote A method reference to the exception constructor with an empty* argument list can be used as the supplier. For example,* {@code IllegalStateException::new}** @param <X> Type of the exception to be thrown* @param exceptionSupplier The supplier which will return the exception to* be thrown* @return the present value* @throws X if there is no value present* @throws NullPointerException if no value is present and* {@code exceptionSupplier} is null*/public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {if (value != null) {return value;} else {throw exceptionSupplier.get();}}/*** Indicates whether some other object is "equal to" this Optional. The* other object is considered equal if:* 指示某个其他对象是否“等于”此可选对象。如果出现以下情况,则另一个对象被视为相等:* <ul>* <li>it is also an {@code Optional} and;* 它也是一个Optional* <li>both instances have no value present or;* 两个实例都不存在值或* <li>the present values are "equal to" each other via {@code equals()}.* 当前值通过 equals() 彼此“相等”* </ul>** @param obj an object to be tested for equality* 一个要测试相等的对象* @return {code true} if the other object is "equal to" this object* otherwise {@code false}** <ul> @param obj @return {code true} 如果另一个对象“等于”这个对象,否则 {@code false}*/@Overridepublic boolean equals(Object obj) {if (this == obj) {return true;}if (!(obj instanceof Optional)) {return false;}Optional<?> other = (Optional<?>) obj;return Objects.equals(value, other.value);}/*** Returns the hash code value of the present value, if any, or 0 (zero) if* no value is present.* 返回当前值的哈希代码值(如果有)或 0(零)(如果不存在任何值)** @return hash code value of the present value or 0 if no value is present*/@Overridepublic int hashCode() {return Objects.hashCode(value);}/*** Returns a non-empty string representation of this Optional suitable for* debugging. The exact presentation format is unspecified and may vary* between implementations and versions.* 返回此 Optional 适合调试的非空字符串表示形式。* 确切的演示格式未指定,可能因实现和版本而异。** @implSpec If a value is present the result must include its string* representation in the result. Empty and present Optionals must be* unambiguously differentiable.* 如果存在值,则结果必须在结果中包含其字符串表示形式。空和存在值的Optionals 必须明确可区分。** @return the string representation of this instance*/@Overridepublic String toString() {return value != null? String.format("Optional[%s]", value): "Optional.empty";}
}相关文章:
java.util.Optional
原文链接 文章目录 1、Optional作用2、常用API构造相关get / orElse / orElseGet / orElseThrowisPresent / ifPresentfiltermap / flatMap 3、源码翻译 1、Optional作用 类位于:java.util.Optional臭名昭著的空指针异常是导致Java应用程序失败的最常见原因&#…...
微服务--Seata(分布式事务)
TCC模式在代码中实现:侵入性强,并且的自己实现事务控制逻辑 Try,Confirm() cancel() 第三方开源框架:BeyeTCC\TCC-transaction\Himly 异步实现:MQ可靠消息最终一致性 GlobalTransacational---AT模式...
发光太阳聚光器的蒙特卡洛光线追踪研究(Matlab代码实现)
💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 ⛳️座右铭&a…...
(涨知识)-圣诞灯串类产品出口都需要做哪些认证?
1. 首先我们讲讲欧盟, 欧盟一向都是合规要求特别多的一个国家,所以向欧盟出口灯串等电子产品,一定要长个心眼。废话不多说,进入正题吧! ①欧盟产品安全:欧代CE(电磁指令EMC低压指令LVD)DOC 产品安全必备三件…...
ROS地图/像素坐标描点调试【Python源码实现】
文章目录 ROS python 地图描点调试工具1. Rviz描点1.1 需求描述1.2 visualization Marker1.3 工程实践 2. 静态地图图片描点2.1 需求描述2.2 工程实践 ROS python 地图描点调试工具 1. Rviz描点 1.1 需求描述 在ROS开发中,有时会加载图片文件转为地图载入move_ba…...
2023年7月京东笔记本电脑行业品牌销售排行榜(京东数据平台)
随着智能手机、平板电脑等移动互联设备的普及,人们对于个人电脑的依赖减轻,加之电脑的更换率较低,因此当前PC端消费市场整体出现疲态,笔记本电脑的出货量不断下降,今年7月份也同样呈现这一趋势。 根据鲸参谋电商数据分…...
用户忠诚度:小程序积分商城的用户保持方法
随着移动互联网的蓬勃发展,小程序积分商城已经成为了许多企业私域营销的热门选择。这个商城不仅可以吸引用户参与,还可以提高用户的忠诚度,进一步加深用户与品牌的互动关系。然而,要实现用户的忠诚度,需要一系列的策略…...
[前端] 使用lerna version更新版本号
lerna version 是一个用于管理 monorepo(多包存储库)的工具,它可以帮助您在多个相关包之间协调版本号的更新和发布。以下是使用 lerna version 更新版本号的一般步骤: 安装 Lerna: 首先,您需要在您的项目中…...
winform嵌入浏览器 webView2
1、项目引用nuget 2、winform窗体中初始化 var webView new WebView2();webView.Source new Uri(url);webView.Dock DockStyle.Fill;//接收js调用c#函数的消息webView.WebMessageReceived CoreWebView2_WebMessageReceivedAsync; this.panel1.Controls.Add(…...
stm32---用外部中断实现红外接收器
一、红外遥控的原理 红外遥控是一种无线、非接触控制技术,具有抗干扰能力强,信息传 输可靠,功耗低,成本低,易实现等显著优点,被诸多电子设备特别是 家用电器广泛采用,并越来越多的应用到计算机系…...
Filter过滤器及HttpServletRequest和HttpServletResponse
拦截器(Interceptor)和过滤器(Filter)的执行顺序 tomcat->Filter->Interceptor->Controller 过滤器(Filter)概述? Filter过滤器是JavaWeb的三大组件之一,三大组件分别为&…...
02-打包代码与依赖
打包代码与依赖说明 在开发中,我们写的应用程序通常需要依赖第三方的库(即程序中引入了既不在 org.apache.spark包,也不再语言运行时的库的依赖),我们就需要确保所有的依赖在Spark应用运行时都能被找到 对于Python而…...
Kotlin(五) 循环语句
目录 For循环 关键字 until step downTo Java中主要有两种循环语句:while循环和for循环。而Kotlin也提供了while循环和for循环,其中while循环不管是在语法还是使用技巧上都和Java中的while循环没有任何区别,因此我们就直接跳过不进行讲解…...
数字孪生产品:数字化时代的变革引擎
数字孪生技术,作为一项前沿的科技创新,正在不断改变我们的世界。它为各行各业的发展提供了无限的可能性,成为了当今数字化时代的一大亮点。数字孪生产品,作为数字孪生技术的具体应用,将在未来发挥越来越重要的作用。 数…...
对接西部数据Western Digital EDI 系统
近期我们为国内某知名电子产品企业提供EDI解决方案,采用知行之桥 EDI 系统作为核心组件,成功与西部数据Western Digital(简称西数)建立EDI连接,实现数据安全且自动化传输。 EDI实施需求 EDI连接 传输协议:A…...
ClickHouse进阶(十):Clickhouse数据查询-4
进入正文前,感谢宝子们订阅专题、点赞、评论、收藏!关注IT贫道,获取高质量博客内容! 🏡个人主页:含各种IT体系技术,IT贫道_Apache Doris,大数据OLAP体系技术栈,Kerberos安全认证-CSDN博客 📌订阅…...
FPGA原理与结构——FIFO IP核的使用与测试
一、前言 本文介绍FIFO Generator v13.2 IP核的具体使用与例化,在学习一个IP核的使用之前,首先需要对于IP核的具体参数和原理有一个基本的了解,具体可以参考: FPGA原理与结构——FIFO IP核原理学习https://blog.csdn.net/apple_5…...
ABB CMA120 3DDE300400面板
人机界面:ABB CMA120 3DDE300400 面板通常具有用户友好的人机界面,可用于监视和控制连接设备和系统的操作。 图形显示:该面板通常具有高分辨率的液晶显示屏,用于显示图形界面和实时数据,以便操作员更容易理解和管理工…...
【代码随想录day25】动态规划:01背包理论基础
题目 有n件物品和一个最多能背重量为w 的背包。第i件物品的重量是weight[i],得到的价值是value[i] 。每件物品只能用一次,求解将哪些物品装入背包里物品价值总和最大。 代码 dp[i][j]: 表示从0~i个物品中选物品放到容量为j的背包中所能获得的最大价值 …...
Python Opencv实践 - 轮廓检测
import cv2 as cv import numpy as np import matplotlib.pyplot as pltimg cv.imread("../SampleImages/map.jpg") print(img.shape) plt.imshow(img[:,:,::-1])#Canny边缘检测 edges cv.Canny(img, 127, 255, 0) plt.imshow(edges, cmapplt.cm.gray)#查找轮廓 #c…...
华为云AI开发平台ModelArts
华为云ModelArts:重塑AI开发流程的“智能引擎”与“创新加速器”! 在人工智能浪潮席卷全球的2025年,企业拥抱AI的意愿空前高涨,但技术门槛高、流程复杂、资源投入巨大的现实,却让许多创新构想止步于实验室。数据科学家…...
在软件开发中正确使用MySQL日期时间类型的深度解析
在日常软件开发场景中,时间信息的存储是底层且核心的需求。从金融交易的精确记账时间、用户操作的行为日志,到供应链系统的物流节点时间戳,时间数据的准确性直接决定业务逻辑的可靠性。MySQL作为主流关系型数据库,其日期时间类型的…...
[2025CVPR]DeepVideo-R1:基于难度感知回归GRPO的视频强化微调框架详解
突破视频大语言模型推理瓶颈,在多个视频基准上实现SOTA性能 一、核心问题与创新亮点 1.1 GRPO在视频任务中的两大挑战 安全措施依赖问题 GRPO使用min和clip函数限制策略更新幅度,导致: 梯度抑制:当新旧策略差异过大时梯度消失收敛困难:策略无法充分优化# 传统GRPO的梯…...
ubuntu搭建nfs服务centos挂载访问
在Ubuntu上设置NFS服务器 在Ubuntu上,你可以使用apt包管理器来安装NFS服务器。打开终端并运行: sudo apt update sudo apt install nfs-kernel-server创建共享目录 创建一个目录用于共享,例如/shared: sudo mkdir /shared sud…...
golang循环变量捕获问题
在 Go 语言中,当在循环中启动协程(goroutine)时,如果在协程闭包中直接引用循环变量,可能会遇到一个常见的陷阱 - 循环变量捕获问题。让我详细解释一下: 问题背景 看这个代码片段: fo…...
el-switch文字内置
el-switch文字内置 效果 vue <div style"color:#ffffff;font-size:14px;float:left;margin-bottom:5px;margin-right:5px;">自动加载</div> <el-switch v-model"value" active-color"#3E99FB" inactive-color"#DCDFE6"…...
vue3+vite项目中使用.env文件环境变量方法
vue3vite项目中使用.env文件环境变量方法 .env文件作用命名规则常用的配置项示例使用方法注意事项在vite.config.js文件中读取环境变量方法 .env文件作用 .env 文件用于定义环境变量,这些变量可以在项目中通过 import.meta.env 进行访问。Vite 会自动加载这些环境变…...
C++八股 —— 单例模式
文章目录 1. 基本概念2. 设计要点3. 实现方式4. 详解懒汉模式 1. 基本概念 线程安全(Thread Safety) 线程安全是指在多线程环境下,某个函数、类或代码片段能够被多个线程同时调用时,仍能保证数据的一致性和逻辑的正确性…...
Swagger和OpenApi的前世今生
Swagger与OpenAPI的关系演进是API标准化进程中的重要篇章,二者共同塑造了现代RESTful API的开发范式。 本期就扒一扒其技术演进的关键节点与核心逻辑: 🔄 一、起源与初创期:Swagger的诞生(2010-2014) 核心…...
站群服务器的应用场景都有哪些?
站群服务器主要是为了多个网站的托管和管理所设计的,可以通过集中管理和高效资源的分配,来支持多个独立的网站同时运行,让每一个网站都可以分配到独立的IP地址,避免出现IP关联的风险,用户还可以通过控制面板进行管理功…...
