天天看點

JAVA中修改順序表中的元素_java – 在清單中查找元素并使用stream()更改它

如果您的目标是隻找到一個元素,那麼您可以這樣做

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,表示調用它的元素數量,這将更容易……