Java - Iterator to Stream

Converting an Iterator to a Stream can be done in two steps:

  1. Convert Iterator to spliterator
  2. 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, iteratorspliteratorstream

Putting everything together in Rept.it

Be Updated

Only articles are shared on Medium