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?
Go to get library AbacusUtil. It provides the exact API you want and more:
Declaration: I'm the developer of AbacusUtil.
Actually there are 2 ways to do it in Java 8 without any extra libraries or using Java 9.
If you want to print numbers from 2 to 20 on the console you can do this:
or
The output is in both cases:
No one mentioned anyMatch yet. This is the reason for this post.
You can't abort a stream except by a short-circuiting terminal operation, which would leave some stream values unprocessed regardless of their value. But if you just want to avoid operations on a stream you can add a transform and filter to the stream:
That transforms the stream of things to nulls when the things meet some condition, then filters out nulls. If you're willing to indulge in side effects, you could set the condition value to true once some thing is encountered, so all subsequent things are filtered out regardless of their value. But even if not you can save a lot of (if not quite all) processing by filtering values out of the stream that you don't want to process.
If you have different problem, different solution may be needed but for your current problem, I would simply go with:
takeWhile
is one of the functions provided by the protonpack library.I have another quick solution by implementing this (which is rly unclean in fact, but you get the idea):