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

当前回答

您可以使用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));

其他回答

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;
});

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

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

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

为了在并行操作中获得最大性能,请使用findAny(),它类似于findFirst()。

Optional<SomeObject> result =
    someObjects.stream().filter(obj -> some_condition_met).findAny();

但是,如果需要稳定的结果,则使用findFirst()。

还要注意匹配模式(anyMatch()/allMatch)将只返回布尔值,你不会得到匹配的对象。

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");
}

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

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