Convert an Iterator to Stream in Java



At first, set an Interator −

Iterator<Integer>iterator = Arrays.asList(50, 100, 200, 400, 500, 1000).iterator();

Now, we have used stream −

Stream<Integer>stream = convertIterator(iterator);

Above, the method convertIterator() is used for conversion. Following is the method −

public static <T> Stream<T> convertIterator(Iterator<T> iterator) {    return StreamSupport.stream(((Iterable) () -> iterator).spliterator(), false); }

Example

Following is the program to convert an Iterator to Stream in Java −

import java.util.stream.*; import java.util.*; public class Demo {    public static <T> Stream<T>    convertIterator(Iterator<T> iterator) {       return StreamSupport.stream(((Iterable) () -> iterator).spliterator(), false);    }    public static void main(String[] args) {       Iterator<Integer>iterator = Arrays.asList(50, 100, 200, 400, 500, 1000).iterator();       Stream<Integer>stream = convertIterator(iterator);       System.out.println("Iterator to Stream...");       stream.forEach(s -> System.out.println(s));    } }

Output

Iterator to Stream... 50 100 200 400 500 1000
Updated on: 2019-09-25T08:37:03+05:30

420 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements