我是一个相对新手的 Stream 用户,我觉得应该有一种更简洁的方法来完成我下面的操作。是否可以在单个 Stream 中完成以下代码的全部操作(消除底部的 if/else)?
谢谢!
Optional<SomeMapping> mapping = allMappings.stream()
.filter(m -> category.toUpperCase().trim().equalsIgnoreCase(m.getCategory().toUpperCase().trim()))
.findAny();
if (mapping.isPresent()) {
return mapping.get();
} else {
throw new SomeException("No mapping found for category \"" + category + "\.");
}
Run Code Online (Sandbox Code Playgroud)
用于orElseThrow在Optional为空时抛出异常:
return
allMappings.stream()
.filter(m -> category.trim().equalsIgnoreCase(m.getCategory().trim()))
.findAny()
.orElseThrow(() -> new SomeException("No mapping found for category \"" + category + "\"."));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |