Convert Iterator to List

Given Iterator<Element>, how can we conveniently convert that Iterator to a List<Element>, so that we can use List's operations on it such as get(index), add(element), etc.


Solution 1:

Better use a library like Guava:

import com.google.common.collect.Lists;

Iterator<Element> myIterator = ... //some iterator
List<Element> myList = Lists.newArrayList(myIterator);

Another Guava example:

ImmutableList.copyOf(myIterator);

or Apache Commons Collections:

import org.apache.commons.collections.IteratorUtils;

Iterator<Element> myIterator = ...//some iterator

List<Element> myList = IteratorUtils.toList(myIterator);       

Solution 2:

In Java 8, you can use the new forEachRemaining method that's been added to the Iterator interface:

List<Element> list = new ArrayList<>();
iterator.forEachRemaining(list::add);