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:
- 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:
// 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)); } } |
chevron_right
filter_none
Output:
1 2 3 4 5
Recommended Posts:
- Creating Sequential Stream from an Iterator in Java
- Convert Iterator to Iterable in Java
- Convert an Iterator to a List in Java
- Java Program to Convert Iterator to Spliterator
- Convert Stream to Set in Java
- Convert a Set to Stream in Java
- Program to convert a Map to a Stream in Java
- Convert an Iterable to Stream in Java
- Program to Convert Stream to an Array in Java
- Program to Convert List to Stream in Java
- Program to convert a Set to Stream in Java using Generics
- Program to convert Primitive Array to Stream in Java
- Program to convert Boxed Array to Stream in Java
- Difference between Stream.of() and Arrays.stream() method in Java
- Character Stream Vs Byte Stream in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



