当在Iterable上使用外部迭代时,我们使用break或return from enhanced for-each循环,如下:
for (SomeObject obj : someObjects) {
if (some_condition_met) {
break; // or return obj
}
}
如何在Java 8 lambda表达式中使用内部迭代中断或返回:
someObjects.forEach(obj -> {
//what to do here?
})
你可以混合使用peek(..)和anyMatch(..)来实现这一点。
举个例子:
someObjects.stream().peek(obj -> {
<your code here>
}).anyMatch(obj -> !<some_condition_met>);
或者写一个通用的util方法:
public static <T> void streamWhile(Stream<T> stream, Predicate<? super T> predicate, Consumer<? super T> consumer) {
stream.peek(consumer).anyMatch(predicate.negate());
}
然后像这样使用它:
streamWhile(someObjects.stream(), obj -> <some_condition_met>, obj -> {
<your code here>
});