Convert an Iterable to Stream in Java
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; class Main { // Generic method to convert an Iterable to a Stream public static <T> Stream<T> iterableToStream(Iterable<T> iterable) { // get spliterator from Iterable and turn it into a sequential stream return StreamSupport.stream(iterable.spliterator(), false); } public static void main(String[] args) { Iterable<String> iterable = Arrays.asList("A", "B", "C", "D"); Stream<String> stream = iterableToStream(iterable); System.out.println(stream.collect(Collectors.toList())); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import com.google.common.collect.Streams; import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.Stream; class Main { // Generic method to convert an Iterable to a Stream public static <T> Stream<T> iterableToStream(Iterable<T> iterable) { // Returns a sequential stream of the contents of the iterable return Streams.stream(iterable); } public static void main(String[] args) { Iterable<String> iterable = Arrays.asList("A", "B", "C", "D"); Stream<String> stream = iterableToStream(iterable); System.out.println(stream.collect(Collectors.toList())); } } |
Output:
[A, B, C, D]
That’s all about converting an Iterable to Stream in Java.
Also See:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)