Exception java 8流——在迭代过程中抛出异常
我有以下数组Exception java 8流——在迭代过程中抛出异常,exception,java-8,java-stream,Exception,Java 8,Java Stream,我有以下数组 ArrayList<Car> list = new ArrayList<>(); 然后我想停止迭代并抛出异常。 有什么办法吗?您可以使用anyMatch来实现: boolean matched = list.stream().anyMatch(x -> x.color.equals("Black")); if(matched) throw new SomeException(); 由于在迭代时,如果一个元素的条件满足,它不会计算管道的其余部分,如果
ArrayList<Car> list = new ArrayList<>();
然后我想停止迭代并抛出异常。有什么办法吗?您可以使用
anyMatch
来实现:
boolean matched = list.stream().anyMatch(x -> x.color.equals("Black"));
if(matched) throw new SomeException();
由于在迭代时,如果一个元素的条件满足,它不会计算管道的其余部分,如果流为空,它将返回false,因此我认为这就是您要寻找的
当然,您可以在一条语句中完成,但根据具体情况,可能无法提高可读性:
if(list.stream().anyMatch(x -> x.color.equals("Black"))) {
throw new SomeException();
}
最简单的是:
list.forEach( x -> {
if(x.color.equals("Black")) throw new RuntimeException();
});
如果使用这种方法,则无需调用
stream()
<代码>列表。forEach就足够了。你当然是对的,我被OP的代码示例蒙蔽了双眼。stream.forEach和forEach之间有什么区别?@rails:不创建流
,但也限于迭代,即不能与forEach
方法相结合,这将允许您抛出选中的异常。
list.forEach( x -> {
if(x.color.equals("Black")) throw new RuntimeException();
});