All topics
library
intermediate

Iterator, ListIterator & Spliterator

Understand the three iteration interfaces, their capabilities, and when Spliterator enables parallel processing.

Java provides three iteration interfaces:

Iterator = a bookmark in a book (forward only). ListIterator = a bookmark you can move both ways. Spliterator = tearing the book in half so two people can read simultaneously.

Key Concepts

1
Iterator<E>: basic forward-only traversal. Methods: hasNext(), next(), remove(). Every Collection implements Iterable<E> which provides iterator(). The enhanced for-loop (for-each) uses Iterator internally.
2
ListIterator<E>: bidirectional traversal for Lists. Adds: hasPrevious(), previous(), nextIndex(), previousIndex(), set(E), add(E). Can iterate forward and backward, modify during iteration.
3
Spliterator<E> (Java 8): designed for parallel iteration. Methods: tryAdvance() (process one element), forEachRemaining() (process all remaining), trySplit() (split into two halves for parallel processing). Reports characteristics: SIZED, ORDERED, SORTED, DISTINCT, etc.
4
Stream API uses Spliterator internally: when you call collection.stream(), it creates a Spliterator. For parallel streams, trySplit() divides the data across threads.
5
Concurrent modification: Iterator throws ConcurrentModificationException if the collection is structurally modified during iteration (except through the iterator's own remove/add). This is 'fail-fast' behavior. ConcurrentHashMap's iterators are 'fail-safe' (weakly consistent).