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

      



  • 相关阅读:
    更改Ubuntu默认python版本的方法
    hdu 5656 CA Loves GCD(dp)
    hdu 5655 CA Loves Stick
    hdu 5650 so easy (异或)
    2016.3.28
    Android 之 ExpandableListView 的使用
    Android之字符串的拆分-split
    Android之SAX解析XML
    hdu 5642 King's Order(数位dp)
    hdu 5641 King's Phone(暴力模拟题)
  • 原文地址:https://www.cnblogs.com/handsomejunhong/p/9132241.html
Copyright © 2011-2022 走看看