从Optional返回值 [英] Return value from Optional
问题描述
如何使用 ifPresent <从
Optional< String>
返回 String
值/ code>并避免 NullPointerException
?
How to return a String
value from an Optional<String>
using ifPresent
and avoiding NullPointerException
?
示例:
public String longestName() {
Optional<String> longName = someList.stream().reduce((name1, name2) -> name1.length() > name2.length() ? name1 : name2);
// If I do not want to use following
// return longName.isPresent() ? longName.get() : "not present";
// Can I achieve this using longName.ifPresent or longName.orElse("not present");
}
推荐答案
返回一个值可选,或者如果可选项没有值,则为默认值,您可以使用 orElse(其他)
。
To return the value of an optional, or a default value if the optional has no value, you can use orElse(other)
.
public String longestName() {
Optional<String> longNameOpt = someList.stream().max(Comparator.comparingInt(String::length));
return longNameOpt.orElse("not present");
}
请注意,我重写了您的代码以找到最长的名称:您可以直接使用 max(比较器)
,比较器比较每个String的长度。可以通过调用 Comparator.comparingInt(keyExtractor)
,键提取器是方法引用 String :: length
。
Note that I rewrote your code for finding the longest name: you can directly use max(comparator)
with a comparator comparing the length of each String. One such comparator can be obtained by calling Comparator.comparingInt(keyExtractor)
with the key extractor being the method reference String::length
.
这篇关于从Optional返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!