[英]If else code execution with Optional class
我在這里看了一個Optional類的教程 - https://www.geeksforgeeks.org/java-8-optional-class/ ,它有以下內容
String[] words = new String[10];
Optional<String> checkNull = Optional.ofNullable(words[5]);
if (checkNull.isPresent()) {
String word = words[5].toLowerCase();
System.out.print(word);
} else{
System.out.println("word is null");
}
我試圖使用ifPresent
檢查Optional
as來減少行ifPresent
Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase()))
但是無法進一步獲得其他部分
Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase())).orElse();// doesn't work```
有辦法嗎?
Java-9在實現中引入了ifPresentOrElse
。 你可以用它作為:
Optional.ofNullable(words[5])
.map(String::toLowerCase) // mapped here itself
.ifPresentOrElse(System.out::println,
() -> System.out.println("word is null"));
使用Java-8,您應該包含一個中間的Optional
/ String
並用作:
Optional<String> optional = Optional.ofNullable(words[5])
.map(String::toLowerCase);
System.out.println(optional.isPresent() ? optional.get() : "word is null");
也可以寫成:
String value = Optional.ofNullable(words[5])
.map(String::toLowerCase)
.orElse("word is null");
System.out.println(value);
或者如果您根本不想將值存儲在變量中,請使用:
System.out.println(Optional.ofNullable(words[5])
.map(String::toLowerCase)
.orElse("word is null"));
為了更清楚ifPresent
將使用Consumer
作為參數並且返回類型為void
,因此您無法對此執行任何嵌套操作
public void ifPresent(Consumer<? super T> consumer)
如果存在值,則使用值調用指定的使用者,否則不執行任何操作。
參數:
consumer - 如果存在值,則執行塊
拋出:
NullPointerException - 如果值存在且consumer為null
因此,而不是ifPreset()
使用map()
String result =Optional.ofNullable(words[5]).map(String::toLowerCase).orElse(null);
打印只是為了打印
System.out.println(Optional.ofNullable(words[5]).map(String::toLowerCase).orElse(null));
如果您使用的是java 9 ,則可以使用ifPresentOrElse()
方法::
Optional.of(words[5]).ifPresentOrElse(
value -> System.out.println(a.toLowerCase()),
() -> System.out.println(null)
);
如果Java 8然后看起來這個偉大的備忘單 :
http://www.nurkiewicz.com/2013/08/optional-in-java-8-cheat-sheet.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.