Java - Iterator to Stream
Converting an Iterator to a Stream can be done in two steps:
- Convert Iterator to spliterator
- Pass the spliterator to stream
1. Converting Iterator to Spliterator
You can convert an Iterator type to a SplitIterator type through Spliterators.spliteratorUnknownSize
API as:
var splitIterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED)
2. Spliterator to stream
To convert Spliterator to Stream, use the StreamSupport.stream
API, which accepts SplitIterator
and a boolean
indicating parallel stream.
Stream<Integer> stream = StreamSupport.stream(splitIterator, false)
In gist,
iterator
→spliterator
→stream