简体   繁体   中英

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.

You can wrap the orignal string in Optional.ofNullable . Assuming checkLength returns a string, the return type of the below would be 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() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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