JAVA 8 Optional类介绍及其源码
什么是Optional对象
Java 8中所谓的Optional对象,即一个容器对象,该对象可以包含一个null或非null值。如果该值不为null,则调用isPresent()方法将返回true,且调用get()方法会返回该值。
另外,该对象还有其它方法:
如可以使用orElse()方法给Optional对象设定默认值(当值为null时,会使用默认值);
使用ifPresent()方法来执行一段代码(当值不为null时,执行代码段)。
Optional主要被用于Java 8的Stream中,简单举个例子:
package optional; import java.util.Optional;
import java.util.stream.Stream; public class Snippet
{
public static void main(String[] args)
{
Stream<String> names = Stream.of("Lamurudu", "Okanbi", "Oduduwa"); Optional<String> startswl = names.filter(name -> name.startsWith("L")).findFirst(); //判断是否不为null
if(startswl.isPresent()){
System.out.println(startswl.get());
} //if值为null:打印“null”;if值不为null:打印原值
System.out.println(startswl.orElse("null")); //if值不为null,执行Lambda表达式
startswl.ifPresent(name -> {
String s = name.toUpperCase();
System.out.println(s);
});
}
}
使用Optional对象的好处
减少NullPointerException异常
写出更加优雅的代码
源码及示例
Optional类的属性和方法如下:
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAdIAAAGbCAIAAAD/VYbFAAAgAElEQVR4nO2dW5QcxZ2n89G7Lzuz6yfW3tnDznI8a1ZjCck2NbNYwjaNQKALSKKRMBdzEnpkY2A42CA3GKQRUhmbRFSby9jG4wsqN94FGyi515Y9PV76yFZZ0JIbMVNugdQgpJbUutHCIInYh6zMjIiMyEtVZFRG1u87eQ5dWZFRkdn0p6iorP/PIl1M7Zf1l3ZPYcOGDZvOzeq0+jpJ7Zd1bNiwYdO8dbV2AQBAP9AuAABoBdoFAACtQLsAAKCVrLT7bwde7//ZxgUV+9z7L/vE+mV3PfPQ7oMT4WYfueFb/pbRSAAAIFeo1+6pM6cf+fWP/rL/ot7vLl39/HX3b/78FwZXLH78ig99Zd5DW77PNYZtAQDdhnrt3jr4wCc3XL5m6MZH/uXvnvr92p/urGza/sDDwzf3v3D9X6+55KnfvUA3zly7DadklZyGkr5qtmXXlPQEAOhiFGv3//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0vw2d0xBWtvxzNqExI7QrznKPm+0KgXYByD0GaFddllrUjJVOMItMRWPuMGAmxc07GUKLDMFigii3TZqTxgWvtbDIAO0CkEcM0K6iLDWhOoXxaOFUNOkCheTDM8lHapLcNuHHevF3MrSiXS8vHR+pAdA5DNAu0ZallisyuW8XANB5zNCuS+ZZajmjlW+pAQByj0naBQCAAgDtAgCAVqBdAADQCrQLAABagXYBAEAr0C4AAGgF2gUAAK1AuwAAoBVotw2CApK5BAE/AOQSaJcjVI8hgja02+o30IJS5fEVbaBdAHJJ92hXWMWLgysSFhQ2VxOpQ4+llXoLI0OBbSfqFbfkDYqKAWAYZmhXRZZaAnuKHaheuy3mpE1Wq4LKYdAuAIZhgHaVZKkFlRipKreiaoucA2vsgf7agGWVnEYgZCZsTVQXkq702GpOGjPbDfZQ8WiugkeG3IdRuWrc4X314TKqQQKgBwO0qyhLjZ60yuLOfE/yMRNMeXLmEZUDxAe1RdQ1byknjRAy5qqzTBW+pGe7E/UK9WxMrhq3ZIEivABowgDtKspSo+wpizujHwd25bUbtORmu9Fha/7DlnPSPJqlyl2NhrQbTIejS56PsdPbMcx2AdCEAdpVlKUWrd2w+IRJwiq023JOGoM/V4V2ATAMA7SrKEstcpHBn4cyH3UFwT+taDdqkaHVnLTmDJdQJm1Vu1hkAKBDGKBdRVlq3tJB1EdqdKpZsJc6MJV2mag2OjytxZw0f3mBvW+XikdLpV23AT5SA0A3BmiXFCNLTZo+nI/vuWGRAQBdmKFdF9Oy1Og1C3ZZIxc5af4XLoi74EDdWAYAyBCTtGse1JpFPua0LMEiA5wLgD6gXQAA0Aq0CwAAWoF2AQBAK9AuAABoBdoFAACtQLsAAKAVaBcAALQC7QIAgFagXQAA0Aq0CwAAWvn/jGlwNX7vdK4AAAAASUVORK5CYII=" alt="" />
我们一个个看,先看两个成员属性;
成员属性
如下,一个是EMPTY常量,即存放空值的Optional对象,另一个是value,即被存放的值,可为null或非null值;
/**
* Common instance for {@code empty()}.
*/
private static final Optional<?> EMPTY = new Optional<>(); /**
* If non-null, the value; if null, indicates no value is present
*/
private final T value;
构造方法
两个构造方法,注意都是私有的
1、创建一个包含空值的Optional对象;
2、创建一个非空值的Optional对象;
private Optional() {
this.value = null;
}
private Optional(T value) {
this.value = Objects.requireNonNull(value);
}
empty()方法
这个方法很简单,作用是返回一个Optional实例,里面存放的value是null,源码如下:
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
of(T value)方法
很简单,就是返回一个包含非空值的Optional对象
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
ofNullable(T value)方法
很简单,返回一个可以包含空值的Optional对象
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
get()方法
得到Optional对象里的值,如果值为null,则抛出NoSuchElementException异常
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
isPresent()方法
很简单,判断值是否不为null
public boolean isPresent() {
return value != null;
}
ifPresent(Consumer<? super T> consumer)方法
当值不为null时,执行consumer
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
举个例子,ifPresent方法执行Lambda表达式,将值转换为大写并打印:
package optional; import java.util.Optional; public class Snippet
{
public static void main(String[] args)
{
Optional<String> test = Optional.ofNullable("abcDef"); //值不为null,执行Lambda表达式,
test.ifPresent(name -> {
String s = name.toUpperCase();
System.out.println(s);
});
//打印ABCDEF
}
}
filter(Predicate<? super T> predicate)方法
看方法名就知道,该方法是过滤方法,过滤符合条件的Optional对象,这里的条件用Lambda表达式来定义,
如果入参predicate对象为null将抛NullPointerException异常,
如果Optional对象的值为null,将直接返回该Optional对象,
如果Optional对象的值符合限定条件(Lambda表达式来定义),返回该值,否则返回空的Optional对象
源码如下:
public Optional<T> filter(Predicate<? super T> predicate) {
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
使用示例:
package optional; import java.util.Optional; public class Snippet
{
public static void main(String[] args)
{
Optional<String> test = Optional.ofNullable("abcD"); //过滤值的长度小于3的Optional对象
Optional<String> less3 = test.filter((value) -> value.length() < 3);
//打印结果
System.out.println(less3.orElse("不符合条件,不打印值!"));
}
}
map(Function<? super T, ? extends U> mapper)方法
前面的filter方法主要用于过滤,一般不会修改Optional里面的值,map方法则一般用于修改该值,并返回修改后的Optional对象
如果入参mapper对象为null将抛NullPointerException异常,
如果Optional对象的值为null,将直接返回该Optional对象,
最后,执行传入的lambda表达式,并返回经lambda表达式操作后的Optional对象
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));
}
}
使用示例:
package optional; import java.util.Optional; public class Snippet
{
public static void main(String[] args)
{
Optional<String> test = Optional.ofNullable("abcD"); //将值修改为大写
Optional<String> less3 = test.map((value) -> value.toUpperCase());
//打印结果 ABCD
System.out.println(less3.orElse("值为null,不打印!"));
}
}
flatMap(Function<? super T, Optional<U>> mapper)方法
flatMap方法与map方法基本一致,唯一的区别是,
如果使用flatMap方法,需要自己在Lambda表达式里将返回值转换成Optional对象,
而使用map方法则不需要这个步骤,因为map方法的源码里已经调用了Optional.ofNullable方法;
源码:
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));
}
}
使用示例:
package optional; import java.util.Optional; public class Snippet
{
public static void main(String[] args)
{
Optional<String> test = Optional.ofNullable("abcD"); //使用flatMap,将值修改为大写
Optional<String> less3 = test.flatMap((value) -> Optional.ofNullable(value.toUpperCase()));
//使用map,将值修改为大写
//Optional<String> less3 = test.map((value) -> value.toUpperCase()); //打印结果 ABCD
System.out.println(less3.orElse("值为null,不打印!"));
}
}
orElse(T other)方法
很简单,当值为null时返回传入的值,否则返回原值;
源码:
public T orElse(T other) {
return value != null ? value : other;
}
orElseGet(Supplier<? extends T> other)方法
功能与orElse(T other)类似,不过该方法可选值的获取不是通过参数直接获取,而是通过调用传入的Lambda表达式获取
源码:
public T orElseGet(Supplier<? extends T> other) {
return value != null ? value : other.get();
}
使用示例:
package optional; import java.util.Optional; public class Snippet
{
public static void main(String[] args)
{
Optional<String> test = Optional.ofNullable(null); System.out.println(test.orElseGet(() -> "hello"));
//将打印hello
}
}
orElseThrow(Supplier<? extends X> exceptionSupplier)方法
当遇到值为null时,根据传入的Lambda表达式跑出指定异常
源码
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
使用示例:
package optional; import java.util.Optional; public class Snippet
{
public static void main(String[] args)
{
Optional<String> test = Optional.ofNullable(null); //这里的Lambda表达式为构造方法引用
System.out.println(test.orElseThrow(NullPointerException::new));
//将打印hello
}
}
参考资料
jdk1.8.0_31源码
https://blog.idrsolutions.com/2015/04/java-8-optional-class-explained-in-5-minutes/
https://www.voxxed.com/blog/2015/05/why-even-use-java-8-optional/
http://unmi.cc/proper-ways-of-using-java8-optional/
JAVA 8 Optional类介绍及其源码的更多相关文章
- Java中Optional类的使用
从 Java 8 引入的一个很有趣的特性是 Optional 类.Optional 类主要解决的问题是臭名昭著的空指针异常(NullPointerException) —— 每个 Java 程序员都 ...
- Java 8 新特性-菜鸟教程 (6) -Java 8 Optional 类
Java 8 Optional 类 Optional 类是一个可以为null的容器对象.如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象. Optional 是个容 ...
- Java 8 Optional 类深度解析
Java 8 Optional 类深度解析 身为一名Java程序员,大家可能都有这样的经历:调用一个方法得到了返回值却不能直接将返回值作为参数去调用别的方法.我们首先要判断这个返回值是否为null,只 ...
- Java 8 Optional类深度解析
身为一名Java程序员,大家可能都有这样的经历:调用一个方法得到了返回值却不能直接将返回值作为参数去调用别的方法.我们首先要判断这个返回值是否为null,只有在非空的前提下才能将其作为其他方法的参数. ...
- Java 8 Optional类深度解析(转)
经常会遇到这样的问题,调用一个方法得到了返回值却不能直接将返回值作为参数去调用别的方法.我们首先要判断这个返回值是否为null,只有在非空的前提下才能将其作为其他方法的参数. 新版本的Java,比如J ...
- Java 8 Optional 类
转自:https://www.runoob.com/java/java8-optional-class.html Optional 类是一个可以为null的容器对象.如果值存在则isPresent() ...
- Java 8 Optional类深度解析(转载)
身为一名Java程序员,大家可能都有这样的经历:调用一个方法得到了返回值却不能直接将返回值作为参数去调用别的方法.我们首先要判断这个返回值是否为null,只有在非空的前提下才能将其作为其他方法的参数. ...
- Java 8 Optional类使用的实践经验
前言 Java中空指针异常(NPE)一直是令开发者头疼的问题.Java 8引入了一个新的Optional类,使用该类可以尽可能地防止出现空指针异常. Optional 类是一个可以为null的容器对象 ...
- [转]Java 8 Optional类深度解析(null处理)
原文链接:http://www.importnew.com/6675.html 本文由 ImportNew - 高俊阳 翻译自 javacodegeeks.欢迎加入翻译小组.转载请见文末要求. 身为一 ...
随机推荐
- js带上框架和防止被iframe的代码
1.永远都会带着框架<script language="JavaScript"><!--if (window == top)top.location.href = ...
- Nlog 记录日志到 sqlite
最近研究了一下Nlog这个日志框架,这里记录一下如何将日志写到sqlite中. 第一步:使用NuGet获取Nlog和Sqlite 第二步:在sqlite中创建一个database,这里我用了SQLit ...
- python 颜色定义
1.颜色定义说明格式:\033[显示方式;前景色;背景色m前景色 背景色 颜色---------------------------------------30 40 黑色31 41 红色32 42 ...
- [小北De编程手记] : Lesson 05 玩转 xUnit.Net 之 从Assert谈UT框架实践
这一篇,本文会介绍一下基本的断言概念,但重点会放在企业级单元测试的相关功能上面.下面来跟大家分享一下xUnit.Net的断言,主要涉及到以下内容: 关于断言的概念 xUnit.Net常用的断言 关于单 ...
- Oracle的AWR报告分析
* 定义:awr报告是oracle 10g下提供的一种性能收集和分析工具,它能提供一个时间段内整个系统资源使用情况的报告,通过这个报告,我们就可以了解一个系统的整个运行情况,这就像一个人全面的体检报告 ...
- Java final数据
许多程序设计语言都有自己的办法告诉编译器某个数据是"常数".常数主要应用于下述两个方面: 1)编译期常数,它永远不会改变: 2)在运行期间初始化的一个值,我们不希望它发生变化.ss ...
- MyBatis入门(一)
一.MyBaris简介 1)MyBaris发展过程 MyBatis的前身叫iBatis,本是apache的一个开源项目, 2010年这个项目由apache software foundation 迁移 ...
- 功能齐全的图表库 ACharts
ACharts是基于Raphael 库开发的,而Raphael.js是基于svg和vml语言,因此最低可以兼容到IE6+,而最高则所有支持w3c svg标准的现代浏览器都可以使用,svg甚至在手机平台 ...
- 提升手持设备点击速度之touch事件带来的坑!
前言 上周六,我将我们项目的click换成了tap事件,于是此事如梦魇一般折磨了我一星期!!! 经过我前仆后继的努力,不计代价的牺牲,不断的埋坑填坑,再埋坑的动作,最后悲伤的发现touch事件确实是个 ...
- 从0开始学angularjs-笔记03
大家好,今天上班第一天,可能大家都不是很想上班吧,我也是一样啦---不想上班就来继续写我的angualrjs教程,造福大家吧!! 今天的主要讲解部分有以下几点:1.演示一个完整的项目结构 2.$sc ...