Skip to main content

How do I read from a stream until a condition is met

In this Q&A, we'll go over how to take from a Stream until a condition is met

Java 9 Stream provides a method takeWhile that allows stream read until a condition is satisfied.
IntStream is = IntStream.of(1,100)
List<Integer> l = is.takeWhile(x-> x <= 7).collect(Collectors.toList());

There is no Java 8 equivalent for this function.  But this StreamUtils project can be used to achieve the same

There is a similar functional dropWhile that filters all elements until a condition is met.

Comments