Friday, December 27, 2024
Google search engine
HomeLanguagesJavaConvert an Iterator to Stream in Java

Convert an Iterator to Stream in Java

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

Examples:

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'}

Approach:

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


Output:

1
2
3
4
5
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments