Stage 5: Collections compared, lesson 7 of 8

Iterator vs ListIterator

Intermediate3 min read@since 8Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

Both walk through elements and let you change the collection safely while iterating.

  • Iterator works with every collection. Methods: hasNext(), next(), remove() and (Java 8) forEachRemaining(). Forward only.
  • ListIterator extends Iterator and works only with lists (list.listIterator(), or listIterator(index) to start in the middle). It adds:
  • both directions: hasPrevious() and previous();
  • positions: nextIndex() and previousIndex();
  • changes: set(e) replaces the last returned element, add(e) inserts at the current position.

Use a for-each loop to just read, an Iterator to remove while looping (or simply removeIf), and a ListIterator to replace, insert or walk backwards.

Side by side

IteratorListIterator
Works withAny CollectionLists only
DirectionForwardForward and backward
Start positionThe beginningAnywhere: listIterator(index)
Removeremove()remove()
ReplaceNoset(e)
InsertNoadd(e)
IndexNonextIndex(), previousIndex()

Example

Java
List<String> names = new ArrayList<>(List.of("asha", "ravi", "meera"));

Iterator<String> it = names.iterator();
while (it.hasNext()) {
    if (it.next().startsWith("r")) it.remove();     // safe removal while iterating
}

ListIterator<String> li = names.listIterator();
while (li.hasNext()) {
    String n = li.next();
    li.set(n.substring(0, 1).toUpperCase() + n.substring(1));   // replace in place: Asha, Meera
    if (n.equals("asha")) li.add("Kiran");                      // insert after Asha
}
System.out.println(names);                          // [Asha, Kiran, Meera]

while (li.hasPrevious()) System.out.print(li.previous() + " ");   // Meera Kiran Asha

Common mistake

Calling list.remove(x) inside a for-each loop over the same list. Use iterator.remove() or list.removeIf(...).

Under the hood

remove() and set() act on the element most recently returned by next() or previous(); calling them before next(), twice in a row, or set() after add() throws IllegalStateException. Changing the list directly (not through the iterator) during iteration throws ConcurrentModificationException on the next step (see "Fail-fast vs fail-safe").

Check yourself

Which method is available on ListIterator but not on Iterator?

How this connects

Where this leads

You've reached the end of this thread. Try a learning path for what's next.

Part of Java 8 and collections, practically.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.