Convert an Iterator to a List in Java

JavaObject Oriented ProgrammingProgramming

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

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

Now, convert this Iterator to a List −

List<Integer> myList = new ArrayList<>();
iterator.forEachRemaining(myList::add);

Example

Following is the program to convert an Iterator to a List in Java −

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String[] args){
      Iterator<Integer> iterator = Arrays.asList(50, 100, 200, 300, 400, 500, 1000).iterator();
      List<Integer> myList = new ArrayList<>();
      iterator.forEachRemaining(myList::add);
      System.out.println("Iterator to list = "+myList);
   }
}

Output

Iterator to list = [50, 100, 200, 300, 400, 500, 1000]
raja
Updated on 26-Sep-2019 13:08:04

Advertisements