zoukankan      html  css  js  c++  java
  • 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()));
            }
    

      



  • 相关阅读:
    反射-基础方法-java
    排序-插入-java
    排序-选择-java
    决策树
    python基础2 -画图
    python基础1
    如何实现用户的历史记录功能(最多n条)
    如何让字典保持有序
    如何快速找到多个字典中的公共键(key)
    如何根据字典中值的大小, 对字典中的项排序
  • 原文地址:https://www.cnblogs.com/handsomejunhong/p/9132241.html
Copyright © 2011-2022 走看看