Convert Iterator to ArrayList

Maksim picture Maksim · Apr 12, 2012 · Viewed 279.8k times · Source

Given Iterator<Element>, how can we convert that Iterator to ArrayList<Element> (or List<Element>) in the best and fastest way possible, so that we can use ArrayList's operations on it such as get(index), add(element), etc.

Answer

Renaud picture Renaud · Jun 11, 2012

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);