JDK8——Optional

Optional

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

容器對象,可能包含也可能不包含非null值。如果存在值,則isPresent()將返回true,get()將返回該值。

Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).

附帶方法依賴於是否存在包含值的方法,例如orElse()(如果值不存在則返回默認值)和ifPresent()(如果值存在則執行代碼塊)。

This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.

這是一個基於值的類,使用身份敏感的操作(包括引用相等(==),標識哈希碼或同步),對於Optional的實例可能會產生不可預測的結果,應該避免。

 

常用的一些方法和場景

isPresent()

Return true if there is a value present, otherwise false.

如果有值就返回true,如果沒有值就返回false,可以用於單元測試的assert判斷,也可以用於對返回值對校驗。

get()

If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.

如果Optional內有值,則返回值,否則拋出異常NoSuchElementException,可以用於返回值是否爲空校驗,前端採用異常攔截器進行攔截處理後返回。

orElseThrow(Supplier<? extends X> exceptionSupplier)

Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

如果前面對計算結果存在,返回包含的值,否則就拋出一個自定義異常,由異常攔截器統一處理後返回。

ofNullable(T value)

Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.

如果指定值非空,則返回指定值;如果爲空,則返回空的Optional,可以用於返回值。

 

學習資料:JDK8官網

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章