Return value from Optional
11,474
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
.
Author by
Pavish Karnik
Updated on June 06, 2022Comments
-
Pavish Karnik almost 2 years
How to return a
String
value from anOptional<String>
usingifPresent
and avoidingNullPointerException
?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"); }
-
Pavish Karnik over 8 yearsreturn longNameOpt.orElse("not present"); was something I was looking for. Thanks