Finite generated Stream in Java - how to create one?
Is there any reasonable easy way to do this in Java, without implementing the entire Stream interface on my own?
A simple .limit()
guarantees that it will terminate. But that's not always powerful enough.
After the Stream
factory methods the simplest approach for creating customs stream sources without reimplementing the stream processing pipeline is subclassing java.util.Spliterators.AbstractSpliterator<T>
and passing it to java.util.stream.StreamSupport.stream(Supplier<? extends Spliterator<T>>, int, boolean)
If you're intending to use parallel streams note that AbstractSpliterator
only yields suboptimal splitting. If you have more control over your source fully implementing the Spliterator
interface can better.
For example, the following snippet would create a Stream providing an infinite sequence 1,2,3...
in that particular example you could use IntStream.range()
But the stream will obviously finish at some point, and terminal operators like (collect() or findAny()) need to work on it.
short-circuiting operations like findAny()
can actually finish on an infinite stream, as long as there is any element that matches.
Java 9 introduces Stream.iterate to generate finite streams for some simple cases.