从 Java Stream 产生的 Optional 中消除额外的 isPresent() 调用
Eliminate extra isPresent() call from Optional produced by Java Stream
我是一个相对新手的 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 + "\.");
}
如果Optional
为空,使用orElseThrow
抛出异常:
return
allMappings.stream()
.filter(m -> category.trim().equalsIgnoreCase(m.getCategory().trim()))
.findAny()
.orElseThrow(() -> new SomeException("No mapping found for category \"" + category + "\"."));
无需使用 toUpperCase()
,因为您正在与 equalsIgnoreCase()
进行比较。
return allMappings.stream().filter(m -> category.trim().equalsIgnoreCase(m.getCategory().trim()))
.findAny()
.orElseThorw (() -> new SomeException("No mapping found for category \"" + category + "\."));
我是一个相对新手的 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 + "\.");
}
如果Optional
为空,使用orElseThrow
抛出异常:
return
allMappings.stream()
.filter(m -> category.trim().equalsIgnoreCase(m.getCategory().trim()))
.findAny()
.orElseThrow(() -> new SomeException("No mapping found for category \"" + category + "\"."));
无需使用 toUpperCase()
,因为您正在与 equalsIgnoreCase()
进行比较。
return allMappings.stream().filter(m -> category.trim().equalsIgnoreCase(m.getCategory().trim()))
.findAny()
.orElseThorw (() -> new SomeException("No mapping found for category \"" + category + "\."));