gpt4 book ai didi

java - 在列表中查找元素并使用 stream() 更改它

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:22:32 26 4
gpt4 key购买 nike

是否可以使用 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();} 也有点笨拙,但据我所知无法简化):

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 代表它被调用的元素的数量,这会更容易......

关于java - 在列表中查找元素并使用 stream() 更改它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066069/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com