Convert an Iterator to a List in Java


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]

Updated on: 26-Sep-2019

270 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements