Sometimes there is a need to convert Iterator
to Stream
to use lambda expression and other functional programming features.
StreamSupport
class provides stream(Spliterator spliterator, boolean parallel)
method which returns Stream
. The second argument in this method is for sequential or parallel stream. We need to provide true for parallel stream.
Iterator
does not have any method to return Spliterator
instance. So we need to use Spliterators.spliteratorUnknownSize()
to get Spliterator
.
import java.util.Arrays; import java.util.Iterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.stream.Stream; import java.util.stream.StreamSupport; public class IterableToStreamExample { public static void main(String[] args) { //Iterator to convert to stream Iterator<String> iterator = Arrays.asList("a", "b", "c") .listIterator(); //Create Spliterator from iterator Spliterator<String> splitIterator = Spliterators .spliteratorUnknownSize(iterator, Spliterator.ORDERED); //Use StreamSupport class to get stream from Iterator Stream<String> stream = StreamSupport.stream(splitIterator, false); //Apply Stream operation stream.forEach(System.out::println); } }
Output
a
b
c