Limit a stream by a predicate

前端 未结 19 3059
别跟我提以往
别跟我提以往 2020-11-21 22:54

Is there a Java 8 stream operation that limits a (potentially infinite) Stream until the first element fails to match a predicate?

In Java 9 we can use

19条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 23:50

    Operations takeWhile and dropWhile have been added to JDK 9. Your example code

    IntStream
        .iterate(1, n -> n + 1)
        .takeWhile(n -> n < 10)
        .forEach(System.out::println);
    

    will behave exactly as you expect it to when compiled and run under JDK 9.

    JDK 9 has been released. It is available for download here: JDK 9 Releases.

提交回复
热议问题