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
raja
Published on 25-Sep-2019 08:34:28
Advertisements