Java 8 Streams - 在迭代过程中抛出异常

Java 8 Streams - Throwing an exception in the middle of an iteration

我有以下数组

ArrayList<Car> list = new ArrayList<>();

我想迭代它,如果它包含某个值就抛出异常

如果至少有一个

list.stream.filter(x -> x.color.equals("Black"));

然后我想停止迭代并抛出异常。
有办法吗?

您可以为此使用 anyMatch

boolean matched = list.stream().anyMatch(x -> x.color.equals("Black"));
if(matched) throw new SomeException();

因为如果在迭代一个元素时满足条件,它不会评估管道的其余部分,并且如果流为空,它 returns false,我想这就是你的意思寻找。

当然,您可以在一条语句中完成,但根据情况可能不会提高可读性:

if(list.stream().anyMatch(x -> x.color.equals("Black"))) {
    throw new SomeException();
}

最简单的是:

list.forEach( x -> {
    if(x.color.equals("Black")) throw new RuntimeException();
});