Limit a stream by a predicate

前端 未结 19 3135
别跟我提以往
别跟我提以往 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:51

    As a follow-up to @StuartMarks answer. My StreamEx library has the takeWhile operation which is compatible with current JDK-9 implementation. When running under JDK-9 it will just delegate to the JDK implementation (via MethodHandle.invokeExact which is really fast). When running under JDK-8, the "polyfill" implementation will be used. So using my library the problem can be solved like this:

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

提交回复
热议问题