Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Collections

The Iterator interface

Reference for java.util.Iterator: hasNext(), next(), remove(), forEachRemaining(), fail-fast behavior and how to write your own Iterable.

An Iterator<E> walks over the elements of a collection one at a time. It is what the enhanced for loop uses behind the scenes: for (String s : list) asks the list for an iterator and then calls hasNext() and next() until nothing is left.

Writing the iterator by hand is useful for one thing that the enhanced for cannot do: removing the current element safely while looping. Any class that implements Iterable<E> (a single method returning an Iterator<E>) can be used in an enhanced for.

Java
Iterator<String> it = list.iterator();
while (it.hasNext()) {
    String s = it.next();
    if (s.isEmpty()) {
        it.remove();
    }
}

Try it

Java Removing while iterating

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Writing your own Iterable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public interface Iterator<E> {
    boolean hasNext();
    E next();
    default void remove();
    default void forEachRemaining(Consumer<? super E> action);
}
Method Description
boolean hasNext() true if another element is available. Does not advance.
E next() Returns the next element and advances. Throws NoSuchElementException when there is none.
void remove() Removes the element returned by the last next(). Optional: the default throws UnsupportedOperationException.
void forEachRemaining(Consumer) Passes every remaining element to the action (Java 8).

Iterable<E> supplies iterator() and the default forEach(Consumer).

Usage notes

  • One-shot: an iterator cannot be rewound. Call iterator() again for a new pass.
  • remove() rules: call it at most once per next(), and not before the first next(). Otherwise you get IllegalStateException.
  • Fail-fast: collections such as ArrayList and HashMap throw ConcurrentModificationException if they are structurally changed during iteration by anything except the iterator's own remove(). This is best effort, not a guarantee, so never rely on it for correctness.
  • Concurrent collections (ConcurrentHashMap, CopyOnWriteArrayList) are weakly consistent or snapshot-based and never throw this exception.
  • Immutable collections (List.of, Map.of) return iterators whose remove() throws UnsupportedOperationException.
  • Order comes from the collection: insertion order for lists and LinkedHashSet, sorted for TreeSet, unspecified for HashSet.
  • Prefer removeIf() for simple conditional removal; it is shorter and, for ArrayList, faster than repeated remove() calls.
  • Enumeration is the legacy predecessor (used by Vector and Hashtable) and has no remove().