Return value from Optional [closed]

元气小坏坏 提交于 2020-01-11 04:13:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!