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.
Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); if (s.isEmpty()) { it.remove(); } }
Try it
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.
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
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 pernext(), and not before the firstnext(). Otherwise you getIllegalStateException.- Fail-fast: collections such as
ArrayListandHashMapthrowConcurrentModificationExceptionif they are structurally changed during iteration by anything except the iterator's ownremove(). 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 whoseremove()throwsUnsupportedOperationException. - Order comes from the collection: insertion order for lists and
LinkedHashSet, sorted forTreeSet, unspecified forHashSet. - Prefer
removeIf()for simple conditional removal; it is shorter and, forArrayList, faster than repeatedremove()calls. Enumerationis the legacy predecessor (used byVectorandHashtable) and has noremove().