Iterables are very useful but provide limited support for lambda expressions. To get other features introduced in Java 8, sometimes there is a need to convert Iterable
to Stream
in Java.
To convert Iterable
to Stream
, we first get a Spliterator
reference.
We then use StreamSupport
class’ stream(Spliterator spliterator, boolean parallel)
method to get Stream
.
The second argument in this method is for sequential or parallel stream. We need to provide true
for parallel stream.
import java.util.Arrays; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class IterableToStreamExample { public static void main(String[] args) { //creating Iterable Iterable<String> iterable = Arrays.asList("a", "b", "c"); //First get Spliterator reference from iterable //second argument 'false' is for sequential/parallel stream Stream<String> stream = StreamSupport.stream(iterable.spliterator(), false); //print stream stream.forEach(System.out::println); } }
Output
a
b
c