Skip to content
Related Articles

Related Articles

Improve Article

Convert an Iterator to Stream in Java

  • Last Updated : 11 Dec, 2018

Given an Iterator, the task is to convert it into Stream in Java.


Input: Iterator = {1, 2, 3, 4, 5}
Output: {1, 2, 3, 4, 5}

Input: Iterator = {'G', 'e', 'e', 'k', 's'}
Output: {'G', 'e', 'e', 'k', 's'}


  1. Get the Iterator.
  2. Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.
  3. Convert the formed Spliterator into Sequential Stream using method.
  4. Return the stream.

Below is the implementation of the above approach:

// Java program to get a Stream
// from a given Iterator
import java.util.*;
class GFG {
    // Function to get the Stream
    public static <T> Stream<T>
    getStreamFromIterator(Iterator<T> iterator)
        // Convert the iterator to Spliterator
            spliterator = Spliterators
                              .spliteratorUnknownSize(iterator, 0);
        // Get a Sequential Stream from spliterator
        return, false);
    // Driver code
    public static void main(String[] args)
        // Get the Iterator
            iterator = Arrays.asList(1, 2, 3, 4, 5)
        // Get the Stream from the Iterator
            stream = getStreamFromIterator(iterator);
        // Print the elements of stream
        stream.forEach(s -> System.out.println(s));

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :