Limit a stream by a predicate
Supercharge your streams in Java with the takeWhile
method. When it encounters a false from the predicate, it wraps up its operation:
Consider this the direct approach to putting a leash on your stream.
Java 8 workaround
Pre-JDK 9 DIY takeWhile
In Java 8, we can roll up our sleeves and craft a similar functionality with Spliterator
and StreamSupport
:
StreamEx to the rescue
StreamEx library does a good "Hold my beer" impression of JDK 9 and offers a takeWhile
method:
StreamEx pulls the rabbit out of the hat with a stellar performance using MethodHandle.invokeExact
.
Protonpack for the win
Protonpack library also has some tricks up its sleeve with a takeWhile
function for Java 8:
Both libraries would make any Java 8 setup punch above its weight by providing ready to use takeWhile
creations.
IntStream and predicate combo
The IntStream iterate
method, sprinkled with some peek
and allMatch
, can also wrangle streams:
Caveat: BreakerException
is used for a break-dance, escaping the operation, which can lead to control freak exceptions.
Efficiency matters
Java 8 version vs Java 9+
While the Java 8 custom takeWhile
is cute, it's slower than a snail race against Java 9's built-in method.
Room for improvement
To enjoy built-in and optimized solutions, consider moving to JDK 9 or later.
StreamEx: More than meets the eye
StreamEx isn't just for takeWhile
voyages. Its documentation is treasure trove of stream operations, worth exploring.
Was this article helpful?