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 StreamSupport.stream() to get a new sequential or parallel Stream.

 

Download   Run Code

Output:

[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 java.util.stream.Stream. 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 StreamSupport.stream() to get a sequential Stream from Spliterator else it simply calls Collection.stream() method.

 

Download   Run Code

Output:

[A, B, C, D]

 

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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz