问题
How to return a String
value from an Optional<String>
using ifPresent
and avoiding NullPointerException
?
Example:
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");
}
回答1:
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");
}
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
.
来源:https://stackoverflow.com/questions/33064398/return-value-from-optional