[英]Find element in a list and change it using stream()
是否可以使用Java 8流在List
查找元素,更改它或在未找到元素时抛出Exception
?
换句话说,我想使用stream
重写以下代码。 我能得到的最好的是更改项目值,但无法确定是否找到/更改了项目。
boolean isFound = false;
for (MyItem item : myList) {
if (item.getValue() > 10) {
item.setAnotherValue(5);
isFound = true;
}
}
if (!isFound) {
throw new ElementNotFoundException("Element 10 wasn't found");
}
如果您的目标是只找到一个元素,那么您可以这样做
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
,这可以稍微简化一下(不幸的是,语法()->{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
,表示调用它的元素数量,这将更容易......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.