In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
本篇文章为大家展示了如何深度解析java8新特性Optional,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
下面以jdk1.8.0_111源码为例
public final class Optional {}
Optional是一个为了解决NullPointerException设计而生可以包含对象也可以包含空的容器对象。封装了很多对空处理的方法也增加了filter、map这样的检索利器,其中函数式编程会有种炫酷到爆的感觉。
基础测试用例对象:
public class Java8OptionalTest { List stringList = null; ICar car = new WeiLaiCar();}public class WeiLaiCar implements ICar { Integer wheels = new Integer(4);}
Api中提供的4种optional
最核心的当属Optional对象,泛型的引入支持了所有对象类型,又增加对常用场景下的double\int\long进行扩展。重点介绍一下Optional对象的方法其他三个类似。
public final class Optional {
public final class OptionalDouble {
public final class OptionalInt {
public final class OptionalLong {
@FunctionalInterface
Predicate\Consumer\Supplier三个接口都是函数式接口
静态方法of
private Optional() {this.value = null;}
构造方法被private,不能new但提供了of这样的静态方法去初始化类;
public static Optional of(T value) { return new Optional(value);}public static Optional ofNullable(T value) { return value == null ? empty() : of(value);}public static Optional empty() { @SuppressWarnings("unchecked") Optional t = (Optional) EMPTY; return t;}
1、empty支持你去创建一个空的optional类,这样的类直接get()会报错:java.util.NoSuchElementException: No value present
2、of(x)传入的对象不能为null,而ofNullable(x)是支持传入null的对象,一般用这两个比较多。
present 方法
isPresent是用来判断optional中对象是否为null,ifPresent的参数是当对象不为null时执行的lamdba表达式。
public boolean isPresent() { return value != null;}public void ifPresent(Consumer
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.