首页 > 解决方案 > 有没有更简洁的方法在这里使用 Optional 而不会在三个地方返回“NA”?

问题描述

    public String getSanitisedMessage() {

        Throwable rootCause = context.getRootCauseException();
        if(rootCause != null) {
            return Optional.ofNullable(rootCause.getMessage())
                    .map(message -> Stream.of(
                            // clean message substrings we want to find
                            "Connection timed out",
                            "Connection reset",
                            "Connection was lost",
                            "FTP Fails"
                    ).filter(subString -> message
                            .toLowerCase()
                            .contains(subString.toLowerCase())
                    ).findFirst().orElse("NA")
                    ).orElse("NA");
        } else return "NA";

    }

目的是检查Throwable's 消息中的子字符串,如果找到则返回子字符串,否则返回NA。两者context.getRootCauseException()Throwable.getMessage()调用都可以返回null

标签: javaoptional

解决方案


一种可能的方法是使用flatMapwithfindFirst而不是mapas:

// method argument is just for the sake of an example and clarification here 
public String getSanitisedMessage(Throwable rootCause, Set<String> primaryCauses) {
    return Optional.ofNullable(rootCause)
            .map(Throwable::getMessage)
            .map(String::toLowerCase)
            .flatMap(message -> primaryCauses.stream()
                    .map(String::toLowerCase)
                    .filter(message::contains)
                    .findFirst())
            .orElse("NA");
}

或者也可以使用三元运算符将其表示为:

return rootCause == null || rootCause.getMessage() == null ? "NA" :
        primaryCauses.stream().map(String::toLowerCase).filter(subString -> rootCause.getMessage()
                .toLowerCase().contains(subString)).findFirst().orElse("NA");

推荐阅读