在文章的开头,先说下NPE问题,NPE问题就是,我们在开发中经常碰到的NullPointerException.假设我们有两个类,他们的UML类图如下图所示
Optional用法 - 图1

在这种情况下,有如下代码

  1. user.getAddress().getProvince();

这种写法,在user为null时,是有可能报NullPointerException异常的。为了解决这个问题,于是采用下面的写法
注 意
文末有:3625页互联网大厂面试题

  1. if(user!=null){
  2. Address address = user.getAddress();
  3. if(address!=null){
  4. String province = address.getProvince();
  5. }
  6. }

这种写法是比较丑陋的,为了避免上述丑陋的写法,让丑陋的设计变得优雅。JAVA8提供了Optional类来优化这种写法,接下来的正文部分进行详细说明

API介绍

先介绍一下API,与其他文章不同的是,本文采取类比的方式来讲,同时结合源码。而不像其他文章一样,一个个API罗列出来,让人找不到重点。
1、Optional(T value),empty(),of(T value),ofNullable(T value)
这四个函数之间具有相关性,因此放在一组进行记忆。
先说明一下,[Optional(T value)](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect),即构造函数,它是private权限的,不能由外部调用的。其余三个函数是public权限,供我们所调用。那么,Optional的本质,就是内部储存了一个真实的值,在构造的时候,就直接判断其值是否为空。好吧,这么说还是比较抽象。直接上[Optional(T value)](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)构造函数的源码,如下图所示
Optional用法 - 图2
那么,of(T value)的源码如下

  1. public static <T> Optional<T> of(T value) {
  2. return new Optional<>(value);
  3. }

也就是说of(T value)函数内部调用了构造函数。根据构造函数的源码我们可以得出两个结论:

除此之外呢,Optional类内部还维护一个value为null的对象,大概就是长下面这样的

  1. public final class Optional<T> {
  2. //省略....
  3. private static final Optional<?> EMPTY = new Optional<>();
  4. private Optional() {
  5. this.value = null;
  6. }
  7. //省略...
  8. public static<T> Optional<T> empty() {
  9. @SuppressWarnings("unchecked")
  10. Optional<T> t = (Optional<T>) EMPTY;
  11. return t;
  12. }
  13. }

那么,empty()的作用就是返回EMPTY对象。
好了铺垫了这么多,可以说ofNullable(T value)的作用了,上源码

  1. public static <T> Optional<T> ofNullable(T value) {
  2. return value == null ? empty() : of(value);
  3. }

好吧,大家应该都看得懂什么意思了。相比较[of(T value)](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)的区别就是,当value值为null时,of(T value)会报NullPointerException异常;[ofNullable(T value)](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)不会throw Exception,[ofNullable(T value)](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)直接返回一个[EMPTY](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)对象。
那是不是意味着,我们在项目中只用[ofNullable](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)函数而不用of函数呢?
不是的,一个东西存在那么自然有存在的价值。当我们在运行过程中,不想隐藏[NullPointerException](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)。而是要立即报告,这种情况下就用Of函数。但是不得不承认,这样的场景真的很少。博主也仅在写junit测试用例中用到过此函数。另外关注:架构师专栏,在后台回复:“面试题”可以获取,高清PDF最新版3625页互联网大厂面试题。
2、orElse(T other),orElseGet(Supplier<? extends T> other)和orElseThrow(Supplier<? extends X> exceptionSupplier)
这三个函数放一组进行记忆,都是在构造函数传入的value值为null时,进行调用的。[orElse](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)[orElseGet](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)的用法如下所示,相当于value值为null时,给予一个默认值:

  1. @Test
  2. public void test() {
  3. User user = null;
  4. user = Optional.ofNullable(user).orElse(createUser());
  5. user = Optional.ofNullable(user).orElseGet(() -> createUser());
  6. }
  7. public User createUser(){
  8. User user = new User();
  9. user.setName("zhangsan");
  10. return user;
  11. }

这两个函数的区别:当user值不为null时,[orElse](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)函数依然会执行createUser()方法,而[orElseGet](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)函数并不会执行createUser()方法,大家可自行测试。
至于orElseThrow,就是value值为null时,直接抛一个异常出去,用法如下所示

  1. User user = null;
  2. Optional.ofNullable(user).orElseThrow(()->new Exception("用户不存在"));

3、[map(Function<? super T, ? extends U> mapper)和flatMap(Function<? super T, Optional<U>> mapper)](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)
这两个函数放在一组记忆,这两个函数做的是转换值的操作。

直接上源码

  1. public final class Optional<T> {
  2. //省略....
  3. public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
  4. Objects.requireNonNull(mapper);
  5. if (!isPresent())
  6. return empty();
  7. else {
  8. return Optional.ofNullable(mapper.apply(value));
  9. }
  10. }
  11. //省略...
  12. public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
  13. Objects.requireNonNull(mapper);
  14. if (!isPresent())
  15. return empty();
  16. else {
  17. return Objects.requireNonNull(mapper.apply(value));
  18. }
  19. }
  20. }

这两个函数,在函数体上没什么区别。唯一区别的就是入参,map函数所接受的入参类型为[Function<? super T, ? extends U>](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect),而flapMap的入参类型为[Function<? super T, Optional<U>>](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)
在具体用法上,对于map而言:
如果User结构是下面这样的

  1. public class User {
  2. private String name;
  3. public String getName() {
  4. return name;
  5. }
  6. }

这时候取name的写法如下所示

  1. String city = Optional.ofNullable(user).map(u-> u.getName()).get();

对于flatMap而言:

如果User结构是下面这样的

  1. public class User {
  2. private String name;
  3. public Optional<String> getName() {
  4. return Optional.ofNullable(name);
  5. }
  6. }

这时候取name的写法如下所示

  1. String city = Optional.ofNullable(user).flatMap(u-> u.getName()).get();

4、isPresent()和ifPresent(Consumer<? super T> consumer)
这两个函数放在一起记忆,[isPresent](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)即判断value值是否为空,而[ifPresent](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)就是在value值不为空时,做一些操作。这两个函数的源码如下

  1. public final class Optional<T> {
  2. //省略....
  3. public boolean isPresent() {
  4. return value != null;
  5. }
  6. //省略...
  7. public void ifPresent(Consumer<? super T> consumer) {
  8. if (value != null)
  9. consumer.accept(value);
  10. }
  11. }

需要额外说明的是,大家千万不要把

  1. if (user != null){
  2. // TODO: do something
  3. }

给写成

  1. User user = Optional.ofNullable(user);
  2. if (Optional.isPresent()){
  3. // TODO: do something
  4. }

因为这样写,代码结构依然丑陋。博主会在后面给出正确写法
至于[ifPresent(Consumer<? super T> consumer)](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect),用法也很简单,如下所示

  1. Optional.ofNullable(user).ifPresent(u->{
  2. // TODO: do something
  3. });

5、filter(Predicate<? super T> predicate)

不多说,直接上源码

  1. public final class Optional<T> {
  2. //省略....
  3. Objects.requireNonNull(predicate);
  4. if (!isPresent())
  5. return this;
  6. else
  7. return predicate.test(value) ? this : empty();
  8. }

filter 方法接受一个 [Predicate](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect) 来对 [Optional](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect) 中包含的值进行过滤,如果包含的值满足条件,那么还是返回这个 Optional;否则返回 [Optional.empty](https://mp.weixin.qq.com/s?__biz=MzA3MTUzOTcxOQ==&mid=2452981393&idx=2&sn=9c0005ed9e5119eef7183eb25db0edee&scene=21#wechat_redirect)

用法如下

  1. Optional<User> user1 = Optional.ofNullable(user).filter(u -> u.getName().length()<6);

如上所示,如果user的name的长度是小于6的,则返回。如果是大于6的,则返回一个EMPTY对象。

实战使用

例一

在函数方法中
以前写法

  1. public String getCity(User user) throws Exception{
  2. if(user!=null){
  3. if(user.getAddress()!=null){
  4. Address address = user.getAddress();
  5. if(address.getCity()!=null){
  6. return address.getCity();
  7. }
  8. }
  9. }
  10. throw new Excpetion("取值错误");
  11. }

JAVA8写法

  1. public String getCity(User user) throws Exception{
  2. return Optional.ofNullable(user)
  3. .map(u-> u.getAddress())
  4. .map(a->a.getCity())
  5. .orElseThrow(()->new Exception("取指错误"));
  6. }

例二

比如,在主程序中
以前写法

  1. if(user!=null){
  2. dosomething(user);
  3. }

JAVA8写法

  1. Optional.ofNullable(user)
  2. .ifPresent(u->{
  3. dosomething(u);
  4. });

例三

以前写法

  1. public User getUser(User user) throws Exception{
  2. if(user!=null){
  3. String name = user.getName();
  4. if("zhangsan".equals(name)){
  5. return user;
  6. }
  7. }else{
  8. user = new User();
  9. user.setName("zhangsan");
  10. return user;
  11. }
  12. }

java8写法

  1. public User getUser(User user) {
  2. return Optional.ofNullable(user)
  3. .filter(u->"zhangsan".equals(u.getName()))
  4. .orElseGet(()-> {
  5. User user1 = new User();
  6. user1.setName("zhangsan");
  7. return user1;
  8. });
  9. }