简体   繁体   English

如何使用Optional进行null检查

[英]How do I do the null check using Optional

I have following method 我有以下方法

public static String convertThreeLetterWordToUpper(String str) {
    String result = Arrays.stream(
            str.split(" ")).map(s-> checkLength(s)).collect(Collectors.joining(" "));
    return result;
}

How can I check if str is not null with out performing a null check and return Optional of result. 如何在不执行空检查的情况下检查str是否不为空,并返回结果的Optional。

You can wrap the orignal string in Optional.ofNullable . 您可以将原始字符串包装在Optional.ofNullable Assuming checkLength returns a string, the return type of the below would be Optional<String> . 假设checkLength返回一个字符串,则下面的返回类型为Optional<String>

Optional.ofNullable(str)
    .map(s -> Arrays.stream(s.split(" "))
                .map(string -> checkLength(string)) 
                .collect(Collectors.joining(" ")));

If you have a default return value to return you can just chain orElse() or can throw an exception with orElseThrow() . 如果您有返回的默认返回值,则可以只链接orElse()或可以使用orElseThrow()引发异常。

String result = Optional.ofNullable(str)
     .map(...)
     .orElse("someDefault");
     //.orElseThrow(() -> new RuntimeException()); Or whatever makes sense

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM