This post 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 in 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. Using Guava Library

Guava release 21.0 introduced several new classes such as Streams, Comparators, MoreCollectors, etc. The Streams class has many utility classes 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 an instance of Collection, this method internally calls StreamSupport.stream() to get a sequential stream from Spliterator; otherwise, it simply calls Collection.stream() method.

Download Code

Output:

[A, B, C, D]

That’s all about converting an Iterable to Stream in Java.

 
Also See:

Create a sequential Stream from an iterator in Java