In Java, one can easily generate an infinite stream with Stream.generate(supplier). However, I would need to generate a stream that will eventually finish.
Imagine, for example, I want a stream of all files in a directory. The number of files can be huge, therefore I can not gather all the data upfront and create a stream from them (via collection.stream()). I need to generate the sequence piece by piece. But the stream will obviously finish at some point, and terminal operators like (collect() or findAny()) need to work on it, so Stream.generate(supplier) is not suitable here.
Is there any reasonable easy way to do this in Java, without implementing the entire Stream interface on my own?
I can think of a simple hack - doing it with infinite Stream.generate(supplier), and providing null or throwing an exception when all the actual values are taken. But it would break the standard stream operators, I could use it only with my own operators that are aware of this behaviour.
CLARIFICATION
People in the comments are proposing me takeWhile() operator. This is not what I meant. How to phrase the question better... I am not asking how to filter (or limit) an existing stream, I am asking how to create (generate) the stream - dynamically, without loading all the elements upfront, but the stream would have a finite size (unknown in advance).
SOLUTION
The code I was looking for is
Iterator it = myCustomIteratorThatGeneratesTheSequence(); StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, Spliterator.DISTINCT), false); I just looked into java.nio.file.Files, how the list(path) method is implemented.
takeWhilelike here stackoverflow.com/q/20746429/1743880?openjdk 9providestakeWhile()Iterator<File>by using this answer stackoverflow.com/a/17959135/3973077 and then convert theIteratorto aStreamusing this one stackoverflow.com/a/24511534/3973077. This way the iterator would only hold a small stack of files in memory and the stream will be lazily evaluated. It's a lot of work though.Spliteratorfits better, before going the lengths of implementing a more complicatedIteratorto wrap it in aSpliteratorafterwards. See this answer for an example…