Fundamentals

Default Methods

Collections

Idioms and Techniques

Design Rationale

Advanced Questions

How can I turn an Iterator into a List?

There is a convenience method on the Collections class:

public static ArrayList list(Enumeration e)

This works for the old Enumeration type, but it seems to be a glaring omission that there is no similar
method for an Iterator. Certainly one could write a loop:

while (iterator.hasNext()) {
    list.add(iterator.next());
}

Unfortunately it’s not possible to use the enhanced-for (“for-each”) loop, since that requires an Iterable.
While it’s possible to convert an Iterator to an Iterable for this purpose, it hardly seems worth it.

In Java 8, Iterator has an extension method forEachRemaining() that takes a lambda. This
allows you to perform this operation very simply. Given Iterator<T> iterator,

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

Using forEachRemaining with a lambda also lets you control the collection type or
even to use a pre-existing collection instance if desired.