Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value from Optional [closed]

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");
}
like image 285
BoltClock Avatar asked May 09 '26 13:05

BoltClock


1 Answers

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.

like image 174
Tunaki Avatar answered May 12 '26 04:05

Tunaki