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

      



  • 相关阅读:
    9.17考试
    Something
    tesuto-Mobius
    7.22考试
    填坑...P1546 最短网络 Agri-Net
    P1125 笨小猴
    P2822 组合数问题
    致我们曾经刷过的水题
    Luogu P1186 玛丽卡
    Luogu P1726 上白泽慧音
  • 原文地址:https://www.cnblogs.com/handsomejunhong/p/9132241.html
Copyright © 2011-2022 走看看