我在这里经历了一个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
作为更少的线
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