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

时间:2016-10-16 01:58:03

标签: java java-8 java-stream

是否有可能在List中找到一个元素,如果找不到该元素,则使用Java 8流来更改它或抛出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");
}

1 个答案:

答案 0 :(得分:6)

如果您的目标只是找到一个元素,那么您可以

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,表示调用它的元素数量,那就更容易了......