How to convert an Iterator or Spliterator to Stream
In this short post I'll show you how to use the StreamSupport utility class introduced in Java 8 to convert a Spliterator or an Iterator to a Stream.
How to convert a Spliterator to a Stream?
The StreamSupport class introduces the stream method which creates a new parallel or sequential stream from the provided Stream. We can take advantage of this method to easily convert the Spliterator into a Stream.
final var input = Arrays.asList(2, 3, 5, 7, 11).spliterator();
StreamSupport.stream(input, false)
.filter(i -> i % 2 == 0)
.forEach(System.out::println);In the previous snippet, I'm converting an array of integers into a Spliterator (line 1). You wouldn't usually do this, since you can directly stream that array (this is just for demo purposes). You would usually end up with a Spliterator instance by consuming a method that returns a value that implements the Spliterator interface.
The second argument in the StreamSupport#stream method (line 2), specifies if the produced stream should be processed in parallel or sequentially. By default, Java processes streams sequentially, it's up to you to switch to parallel in case your pipeline supports it and you can take advantage of it.
If we execute the previous snippet, the console will show the following output:
2How to convert an Iterator to a Stream?
Now that I've showed you how to go from a Spliterator to a Stream, I can show you how to achieve the same with an Iterator. The trick here is to convert the Iterator to a Spliterator first, and then repeat the process I described before.
final var iterator = Arrays.asList(2, 3, 5, 7, 11).iterator();
final var input = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED);
StreamSupport.stream(input, false)
.filter(i -> i % 2 == 0)
.forEach(System.out::println);In the previous snippet, I'm using the Spliterators#spliteratorUnknownSize method (line 2) to convert the Iterator. This provides me with the Spliterator instance that can be processed just like before.
References
- java.util.stream.StreamSupport Javadoc
- java.util.Spliterators Javadoc
