Convert an Iterable to Stream in Java

In this post, we will discuss how to convert an Iterable to Stream in Java.


1. Using Spliterators

The Iterable interface did not provide stream() or parallelStream() methods, mainly due to design issues to avoid unpredictable results. The technical discussion can be found on this thread. Instead they added spliterator() default method to the Iterable interface.

So the idea is to get Spliterator over the elements described by the Iterable by calling its spliterator() method and then pass the Spliterator to to get a new sequential or parallel Stream.


Download   Run Code


[A, B, C, D]


2. Guava library

Guava release 21.0 introduced several new classes such as Streams, Comparators, MoreCollectors, etc. The Streams class has many utility class for working with One such method is stream() which can create a sequential Stream of the contents of the iterable.

Please note that if the Iterable is not a instance of Collection, this method internally calls to get a sequential Stream from Spliterator else it simply calls method.


Download   Run Code


[A, B, C, D]


Also See: Create a Sequential Stream from an Iterator in Java

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of