Java Streams API 中有很多关于 peek
的问题。我正在寻找一种使用 Java Streams 完成以下常见模式的方法。我可以使用 Streams 让它工作,但是这并不明显,意味着没有注释会稍微危险,这并不理想。
boolean anyPricingComponentsChanged = false;
for (var pc : plan.getPricingComponents()) {
if (pc.getValidTill() == null || pc.getValidTill().compareTo(dateNow) <= 0) {
anyPricingComponentsChanged = true;
pc.setValidTill(dateNow);
}
}
我的选项:
long numberChanged = plan.getPricingComponents()
.stream()
.filter(pc -> pc.getValidTill() == null || pc.getValidTill().compareTo(dateNow) <= 0)
.peek(pc -> pc.setValidTill(dateNow))
.count(); //`count` rather than `findAny` to ensure that `peek` processes all components.
boolean anyPricingComponentsChanged = numberChanged != 0;
顺便提一下,虽然在这里compareTo
不是一个昂贵的操作并且始终返回相同的结果,但在其他情况下可能并非如此,我宁愿避免为此模式运行多次。