java - 有没有更简洁的方法在这里使用 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
。
解决方案
一种可能的方法是使用flatMap
withfindFirst
而不是map
as:
// 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");
推荐阅读
- python - 为什么我的 Numpy 掩码不适用于 OpenCV bitwiseAnd()?
- python - 如果列下该行中的任何单元格不是浮点数,如何删除数据框中的行?
- python - Flask 网页 - 需要显示用户列表并允许管理员选择多个条目
- sql - 使用 XML 数据对列进行 MSSQL 混淆
- laravel - 如何在 Laravel 中通过“ids”获取和分享不同网页的帖子?
- html - 无法获取褪色的浮动ui对话框;不显示在闪亮
- spring - 连接到 WebSocket 时 WebSocketClient 冻结(Spring WebFlux)
- kubernetes - 在工作节点(或)由于内存使用而挂起的节点中停止 Kubelet 服务使 MYSQL 无法在 Kubernetes 工作节点中正确终止
- spring - Spring Boot 找不到在外部目录中声明的属性文件
- java - IntelliJ Idea:关于 Java 11 上支持的注释处理器源版本“RELEASE_6”的 Maven 编译警告