JAVA 8 Optional的使用

Optional 是JAVA8 新增的一个API,主要用于避免出现空指针的情况。

以前若一个要对一个类进行空指针的判断,就需要写很多的if,else。代码看起来十分不优雅。

所以JAVA8就推出了Optional这个API对空指针进行处理。

——————————————————————————————————————————

对于我自己来说,这个API用的最多的就是。

of
ofNullable
isPresent
ifPresent
map

以上五个方法。  下面依次讲一下用法。

of 和 ofNullable  都是用于构造Optional的方法,还有一种方法是empty,但是我个人还没有用过这个方法。

of 和 ofNullable 最大的区别就是一个是不允许传入null值,一个是允许传入null值。

isPresent 相当于 obj != null

ifPresent 相当于 if(obj != null) 后面可接lambda

map:用于取值

下面给一个综合的例子:

SalesDistributor salesDistributor = salesDistributorService.findById(parameter.getPaymenterId());
        Optional<SalesDistributor> optional = Optional.ofNullable(salesDistributor);
        if (optional.isPresent()) {
            Optional<String> financialAccountId =
                    optional
                            .map(SalesDistributor::getFinancialAccount)
                            .map(a -> a.getId());
            financialAccountId.ifPresent(s -> parameter.setPaymenterId(financialAccountId.get()));
        }

  



猜你喜欢

转载自www.cnblogs.com/handsomejunhong/p/9132241.html