Man*_*ani 9 java optional java-8
我在这里看了一个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");
}
Run Code Online (Sandbox Code Playgroud)
我试图通过ifPresent检查Optionalas 来减少行数
Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase()))
Run Code Online (Sandbox Code Playgroud)
但是无法进一步获得其他部分
Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase())).orElse();// doesn't work```
Run Code Online (Sandbox Code Playgroud)
有办法吗?
Nam*_*man 12
Java-9 ifPresentOrElse在实现中引入了类似的东西.你可以用它作为:
Optional.ofNullable(words[5])
.map(String::toLowerCase) // mapped here itself
.ifPresentOrElse(System.out::println,
() -> System.out.println("word is null"));
Run Code Online (Sandbox Code Playgroud)
使用Java-8,您应该包含一个中间Optional/ String并用作:
Optional<String> optional = Optional.ofNullable(words[5])
.map(String::toLowerCase);
System.out.println(optional.isPresent() ? optional.get() : "word is null");
Run Code Online (Sandbox Code Playgroud)
也可以写成:
String value = Optional.ofNullable(words[5])
.map(String::toLowerCase)
.orElse("word is null");
System.out.println(value);
Run Code Online (Sandbox Code Playgroud)
或者如果您根本不想将值存储在变量中,请使用:
System.out.println(Optional.ofNullable(words[5])
.map(String::toLowerCase)
.orElse("word is null"));
Run Code Online (Sandbox Code Playgroud)