当在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?
})

当前回答

下面是我在一个项目中使用的解决方案。相反,forEach只需使用allMatch:

someObjects.allMatch(obj -> {
    return !some_condition_met;
});

其他回答

public static void main(String[] args) {
    List<String> list = Arrays.asList("one", "two", "three", "seven", "nine");
    AtomicBoolean yes = new AtomicBoolean(true);
    list.stream().takeWhile(value -> yes.get()).forEach(value -> {
        System.out.println("prior cond" + value);
        if (value.equals("two")) {
            System.out.println(value);
            yes.set(false);
        }

    });
    //System.out.println("Hello World");
}

我建议使用anyMatch。例子:-

return someObjects.stream().anyMatch(obj -> 
    some_condition_met;
);

你可以参考这篇文章来理解anyMatch:- https://beginnersbook.com/2017/11/java-8-stream-anymatch-example/

你可以混合使用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>
});

更新到Java 9+与takeWhile:

MutableBoolean ongoing = MutableBoolean.of(true);
someobjects.stream()...takeWhile(t -> ongoing.value()).forEach(t -> {
    // doing something.
    if (...) { // want to break;
        ongoing.setFalse();
    }
});

下面是我在一个项目中使用的解决方案。相反,forEach只需使用allMatch:

someObjects.allMatch(obj -> {
    return !some_condition_met;
});