Limit a stream by a predicate
java, java-8, java-stream
Solution
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.
Problem
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 `takeWhile` as in the example below to print all the numbers less than 10. ``` IntStream .iterate(1, n -> n + 1) .takeWhile(n -> n < 10) .forEach(System.out::println); ``` As there is no such operation in Java 8, what's the best way of implementing it in a general way?