Convert Iterator to Iterable in Java


Let’s say the following is our Iterator with Integer values −

Iterator<Integer>iterator = Arrays.asList(20, 40, 60, 80, 100, 120, 150, 200).iterator();

Now, convert the Iterator to Iterable −

Iterable<Integer>iterable = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0),false).collect(Collectors.toList());

Example

Following is the program to convert Iterator to Iterable in Java −

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class Demo {
   public static void main(String[] args) {
      Iterator<Integer>iterator = Arrays.asList(20, 40, 60, 80, 100, 120, 150, 200).iterator();
      Iterable<Integer>iterable = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false).collect(Collectors.toList());
      System.out.println("Iterable = ");
      iterable.forEach(System.out::println);
   }
}

Output

Iterable =
20
40
60
80
100
120
150
200
raja
Published on 25-Sep-2019 08:54:06
Advertisements