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

当前回答

我建议使用anyMatch。例子:-

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

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

其他回答

int valueToMatch = 7;
Stream.of(1,2,3,4,5,6,7,8).anyMatch(val->{
   boolean isMatch = val == valueToMatch;
   if(isMatch) {
      /*Do whatever you want...*/
       System.out.println(val);
   }
   return isMatch;
});

它只会在找到匹配的地方执行操作,在找到匹配后停止迭代。

您可以使用java8 + rxjava。

//import java.util.stream.IntStream;
//import rx.Observable;

    IntStream intStream  = IntStream.range(1,10000000);
    Observable.from(() -> intStream.iterator())
            .takeWhile(n -> n < 10)
            .forEach(n-> System.out.println(n));

lambda中的return等于for-each中的continue,但不等同于break。你可以直接返回继续:

someObjects.forEach(obj -> {
   if (some_condition_met) {
      return;
   }
})

更新到Java 9+与takeWhile:

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

我建议使用anyMatch。例子:-

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

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