如果您的目标是只找到一个元素,那么您可以这样做
MyItem item = l.stream()
.filter(x -> x.getValue() > 10)
.findAny() // here we get an Optional
.orElseThrow(() -> new RuntimeException("Element 10 wasn't found"));
item.setAnotherValue(4);
在Java 9中,使用ifPresentOrElse,这可以稍微简化为(遗憾的是,syntax() – > {throw new RuntimeException();}也有点笨拙,但AFAIK它不能简化):
l.stream()
.filter(x -> x.getValue() > 10)
.findAny() // here we get an Optional
.ifPresentOrElse(x->x.setAnotherValue(5),
()->{throw new RuntimeException();});
如果你想为所有项目做这件事,你可以试试这样的事情.但由于Java 8 Streams不是为了通过副作用而设计的,所以这不是一个非常干净的方法:
AtomicBoolean b = new AtomicBoolean(false);
l.stream()
.filter(x -> x.getValue() > 10)
.forEach(x->{
x.setAnotherValue(5);
b.set(true);
});
if (b.get()){
throw new RuntimeException();
}
当然,您也可以简单地将元素收集到列表中,然后执行操作.但我不确定这是否比你开始使用的简单for循环有任何改进……
好吧,如果forEach返回一个long,表示调用它的元素数量,这将更容易……