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…...

手游刚开服就被攻击怎么办?如何防御DDoS?
开服初期是手游最脆弱的阶段,极易成为DDoS攻击的目标。一旦遭遇攻击,可能导致服务器瘫痪、玩家流失,甚至造成巨大经济损失。本文为开发者提供一套简洁有效的应急与防御方案,帮助快速应对并构建长期防护体系。 一、遭遇攻击的紧急应…...

【Python】 -- 趣味代码 - 小恐龙游戏
文章目录 文章目录 00 小恐龙游戏程序设计框架代码结构和功能游戏流程总结01 小恐龙游戏程序设计02 百度网盘地址00 小恐龙游戏程序设计框架 这段代码是一个基于 Pygame 的简易跑酷游戏的完整实现,玩家控制一个角色(龙)躲避障碍物(仙人掌和乌鸦)。以下是代码的详细介绍:…...

centos 7 部署awstats 网站访问检测
一、基础环境准备(两种安装方式都要做) bash # 安装必要依赖 yum install -y httpd perl mod_perl perl-Time-HiRes perl-DateTime systemctl enable httpd # 设置 Apache 开机自启 systemctl start httpd # 启动 Apache二、安装 AWStats࿰…...

Cinnamon修改面板小工具图标
Cinnamon开始菜单-CSDN博客 设置模块都是做好的,比GNOME简单得多! 在 applet.js 里增加 const Settings imports.ui.settings;this.settings new Settings.AppletSettings(this, HTYMenusonichy, instance_id); this.settings.bind(menu-icon, menu…...
unix/linux,sudo,其发展历程详细时间线、由来、历史背景
sudo 的诞生和演化,本身就是一部 Unix/Linux 系统管理哲学变迁的微缩史。来,让我们拨开时间的迷雾,一同探寻 sudo 那波澜壮阔(也颇为实用主义)的发展历程。 历史背景:su的时代与困境 ( 20 世纪 70 年代 - 80 年代初) 在 sudo 出现之前,Unix 系统管理员和需要特权操作的…...
MySQL用户和授权
开放MySQL白名单 可以通过iptables-save命令确认对应客户端ip是否可以访问MySQL服务: test: # iptables-save | grep 3306 -A mp_srv_whitelist -s 172.16.14.102/32 -p tcp -m tcp --dport 3306 -j ACCEPT -A mp_srv_whitelist -s 172.16.4.16/32 -p tcp -m tcp -…...
管理学院权限管理系统开发总结
文章目录 🎓 管理学院权限管理系统开发总结 - 现代化Web应用实践之路📝 项目概述🏗️ 技术架构设计后端技术栈前端技术栈 💡 核心功能特性1. 用户管理模块2. 权限管理系统3. 统计报表功能4. 用户体验优化 🗄️ 数据库设…...

排序算法总结(C++)
目录 一、稳定性二、排序算法选择、冒泡、插入排序归并排序随机快速排序堆排序基数排序计数排序 三、总结 一、稳定性 排序算法的稳定性是指:同样大小的样本 **(同样大小的数据)**在排序之后不会改变原始的相对次序。 稳定性对基础类型对象…...

Qemu arm操作系统开发环境
使用qemu虚拟arm硬件比较合适。 步骤如下: 安装qemu apt install qemu-system安装aarch64-none-elf-gcc 需要手动下载,下载地址:https://developer.arm.com/-/media/Files/downloads/gnu/13.2.rel1/binrel/arm-gnu-toolchain-13.2.rel1-x…...

nnUNet V2修改网络——暴力替换网络为UNet++
更换前,要用nnUNet V2跑通所用数据集,证明nnUNet V2、数据集、运行环境等没有问题 阅读nnU-Net V2 的 U-Net结构,初步了解要修改的网络,知己知彼,修改起来才能游刃有余。 U-Net存在两个局限,一是网络的最佳深度因应用场景而异,这取决于任务的难度和可用于训练的标注数…...