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()));
            }
    

      



  • 相关阅读:
    牛客寒假算法集训 1
    求逆序数——树状数组
    牛客网 被3整除的子序列 区间dp
    SICNU 2019 winter training #2(codeforces #531 Div3)
    iOS 给已有的类添加属性.
    coredata实践
    IOS 数据库升级
    获取当前屏幕显示的viewcontroller
    ios 自顶一个view
    mac 修改文件夹权限.
  • 原文地址:https://www.cnblogs.com/handsomejunhong/p/9132241.html
Copyright © 2011-2022 走看看