从Optional返回值 [英] Return value from Optional

查看:1207
本文介绍了从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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆