Java8-7-Optional類詳解

上一篇咱們詳細介紹了Predicate函數式接口中主要的一些方法使用,本篇介紹的Optional雖然並非一個函數式接口,可是也是一個極其重要的類。segmentfault

Optional並非咱們以前介紹的一系列函數式接口,它是一個class,主要做用就是解決Java中的NPE(NullPointerException)。空指針異常在程序運行中出現的頻率很是大,咱們常常遇到須要在邏輯處理前判斷一個對象是否爲null的狀況。函數

if(null != person){
    Address address = person.getAddress();
    if(null != address){
        ......
    }
}

實際開發中咱們常常會按上面的方式進行非空判斷,接下來看下使用Optional類如何避免空指針問題指針

String str = "hello";
Optional<String> optional = Optional.ofNullable(str);
optional.ifPresent(s -> System.out.println(s));//value爲hello,正常輸出

首先,ofNullable方法接收一個可能爲null的參數,將參數的值賦給Optional類中的成員變量value,ifPresent方法接收一個Consumer類型函數式接口實例,再將成員變量value交給Consumer的accept方法處理前,會校驗成員變量value是否爲null,若是value是null,則什麼也不會執行,避免了空指針問題。下方是ifPresent源碼code

/**
 * If a value is present, invoke the specified consumer with the value,
 * otherwise do nothing.
 *
 * @param consumer block to be executed if a value is present
 * @throws NullPointerException if value is present and {@code consumer} is
 * null
 */
public void ifPresent(Consumer<? super T> consumer) {
    if (value != null)
        consumer.accept(value);
}

若是傳入的內容是空,則什麼也不會執行,也不會有空指針異常對象

String str = null;
Optional<String> optional = Optional.ofNullable(str);
optional.ifPresent(s -> System.out.println(s));//不會輸出任何內容

若是爲空時想返回一個默認值接口

String str = null;
Optional<String> optional = Optional.ofNullable(str);
System.out.println(optional.orElseGet(() -> "welcome"));

orElseGet方法接收一個Supplier,還記得前面介紹的Supplier麼,不接受參數經過get方法直接返回結果,相似工廠模式,上面代碼就是針對傳入的str變量,若是不爲null那正常輸出,若是爲null,那返回一個默認值"welcome"ci

orElseGet方法源碼開發

/**
 * Return the value if present, otherwise invoke {@code other} and return
 * the result of that invocation.
 *
 * @param other a {@code Supplier} whose result is returned if no value
 * is present
 * @return the value if present otherwise the result of {@code other.get()}
 * @throws NullPointerException if value is not present and {@code other} is
 * null
 */
public T orElseGet(Supplier<? extends T> other) {
    return value != null ? value : other.get();
}

下一篇get

相關文章
相關標籤/搜索