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.
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:
- Get the Iterator.
- Convert the iterator to Spliterator using Spliterators.spliteratorUnknownSize() method.
- Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.
- Return the stream.
Below is the implementation of the above approach:
import java.util.*;
import java.util.stream.*;
class GFG {
public static <T> Stream<T>
getStreamFromIterator(Iterator<T> iterator)
{
Spliterator<T>
spliterator = Spliterators
.spliteratorUnknownSize(iterator, 0 );
return StreamSupport.stream(spliterator, false );
}
public static void main(String[] args)
{
Iterator<Integer>
iterator = Arrays.asList( 1 , 2 , 3 , 4 , 5 )
.iterator();
Stream<Integer>
stream = getStreamFromIterator(iterator);
stream.forEach(s -> System.out.println(s));
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...