Iterator vs ListIterator
Iterator walks forward through any collection and can remove what it just returned. ListIterator, which only lists provide, can also move backwards, report positions, replace elements and insert new ones. This page explains the cursor model both share, runs every method with its rules, writes a custom Iterable, and covers the older Enumeration and iterating maps.
Contents
The cursor model Iterator basics ListIterator: replace, insert and walk backwards The rules for remove, set and add Writing your own Iterable Enumeration and iterating maps Fail-fast and weakly consistent iterators Spliterator: the iterator behind streams Index loop or iterator: the cost on each list type Which one to use
The cursor model
An iterator is a cursor that sits between elements, never on one. Before the first call it is in front of the first element. next()hasNext()remove()set()
IteratorCollectioniterator()ListIterator
| Capability | Iterator | ListIterator |
|---|---|---|
| Available on | Every Collection | ListlistIterator() |
Move forward: hasNextnext | Yes | Yes |
Move backward: hasPreviousprevious | No | Yes |
Positions: nextIndexpreviousIndex | No | Yes |
| Remove the current element | remove() | remove() |
| Replace the current element | No | set(e) |
| Insert at the cursor | No | add(e) |
| Start in the middle | No | listIterator(index) |
| Process the rest with a lambda | forEachRemaining | Inherited |
Both kinds of iterator over the standard collections are fail-fast: if the collection is changed by anything other than the iterator itself, the next call throws ConcurrentModificationExceptionremovesetadd
Iterator basics
A set of tags shows that Iterator
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.TreeSet;
public class IteratorBasics {
public static void main(String[] args) {
// Iterator works on every Collection, including sets that have no index
Set<String> tags = new TreeSet<>(Set.of("java", "sql", "go"));
Iterator<String> it = tags.iterator();
while (it.hasNext()) {
System.out.println("tag: " + it.next());
}
// It only moves forward, once. Calling next() at the end throws
try {
it.next();
} catch (NoSuchElementException e) {
System.out.println("next() past the end: NoSuchElementException");
}
// A for-each loop is compiled to exactly this hasNext/next pattern
for (String t : List.of("a", "b")) {
System.out.println("for-each: " + t);
}
}
}
Output:
tag: go
tag: java
tag: sql
next() past the end: NoSuchElementException
for-each: a
for-each: b
- The
loop visits every element. Awhile (it.hasNext()) returns them in sorted order; aTreeSet would use its own order.HashSet - Calling
whennext() is false throwshasNext() , never returnsNoSuchElementException .null - The for-each loop compiles to the same
,iterator() andhasNext() calls. Write the explicit form only when you neednext() , as on theremove()removing while iterating page .
ListIterator: replace, insert and walk backwards
The word list is edited in a single forward pass, with one word replaced, one removed and one inserted, and then read backwards with the same kind of iterator.
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class ListIteratorDemo {
public static void main(String[] args) {
List<String> words = new ArrayList<>(List.of("one", "TWO", "three", "FOUR"));
// set, add and remove during one pass
ListIterator<String> it = words.listIterator();
while (it.hasNext()) {
int index = it.nextIndex();
String w = it.next();
if (w.equals(w.toUpperCase())) {
it.set(w.toLowerCase()); // replace the element just returned
}
if (w.equals("three")) {
it.add("three-and-a-half"); // insert after it; the loop skips it
}
if (w.equals("one")) {
it.remove(); // delete the element just returned
}
System.out.println("visited index " + index + ": " + w);
}
System.out.println("result: " + words);
// Walk backwards, starting at the end
ListIterator<String> back = words.listIterator(words.size());
StringBuilder reversed = new StringBuilder();
while (back.hasPrevious()) {
reversed.append(back.previous()).append(' ');
}
System.out.println("backwards: " + reversed.toString().trim());
}
}
Output:
visited index 0: one
visited index 0: TWO
visited index 1: three
visited index 3: FOUR
result: [two, three, three-and-a-half, four]
backwards: four three-and-a-half three two
reports where the cursor is. AfternextIndex() was removed, the next element,one , also reported index 0, because everything shifted left.TWO replacedset withTWO in place.two insertedadd right afterthree-and-a-half , before the cursor, so the loop did not visit it and went straight on tothree at index 3.FOUR starts with the cursor after the last element, andlistIterator(list.size()) walks back to the start. Since Java 21,previous() is a simpler way to loop backwards when no editing is needed.list.reversed()
The rules for remove, set and add
removesetadd
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
public class CursorRules {
public static void main(String[] args) {
List<Character> letters = new ArrayList<>(List.of('a', 'b', 'c'));
ListIterator<Character> it = letters.listIterator();
// The cursor sits BETWEEN elements: ^a b c
System.out.println("nextIndex=" + it.nextIndex());
System.out.println("previousIndex=" + it.previousIndex());
it.next(); // a ^b c
it.next(); // a b ^c
System.out.println("after two next(): nextIndex=" + it.nextIndex());
System.out.println("previous() = " + it.previous() + " (cursor back to a ^b c)");
// set() is not allowed right after add()
it.add('X'); // a X ^b c
try {
it.set('Y');
} catch (IllegalStateException e) {
System.out.println("set() after add(): IllegalStateException");
}
System.out.println("list: " + letters);
}
}
Output:
nextIndex=0
previousIndex=-1
after two next(): nextIndex=2
previous() = b (cursor back to a ^b c)
set() after add(): IllegalStateException
list: [a, X, b, c]
- At the start,
is 0 andnextIndex() is -1. After twopreviousIndex() calls the cursor is betweennext() andb , soc is 2.nextIndex() returnsprevious() again: moving back jumps over the element just returned. Alternatingb andnext returns the same element each time.previous- After
, there is no current element, soadd threwset . The same happens forIllegalStateException orremove before the firstset , and for twonext calls in a row.remove - The inserted
went in at the cursor position, beforeX .b
Writing your own Iterable
Any class that implements Iterable<T>
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.stream.StreamSupport;
public class CustomIterable {
// A range of even numbers that computes its elements on demand, without a list
record EvenRange(int from, int to) implements Iterable<Integer> {
@Override
public Iterator<Integer> iterator() {
return new Iterator<>() {
private int next = from % 2 == 0 ? from : from + 1;
@Override
public boolean hasNext() {
return next <= to;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
int value = next;
next += 2;
return value;
}
};
}
}
public static void main(String[] args) {
EvenRange range = new EvenRange(3, 11);
StringBuilder sb = new StringBuilder();
for (int x : range) { // for-each works on any Iterable
sb.append(x).append(' ');
}
System.out.println("for-each: " + sb.toString().strip());
// Each call to iterator() starts a fresh, independent pass
Iterator<Integer> a = range.iterator();
Iterator<Integer> b = range.iterator();
a.next();
a.next();
System.out.println("independent: a.next()=" + a.next() + ", b.next()=" + b.next());
// forEachRemaining consumes whatever is left
StringBuilder rest = new StringBuilder();
a.forEachRemaining(x -> rest.append(x).append(' '));
System.out.println("forEachRemaining: " + rest.toString().strip());
// remove() is optional: the default implementation throws
try {
range.iterator().remove();
} catch (UnsupportedOperationException e) {
System.out.println("remove(): UnsupportedOperationException (default method)");
}
// An Iterable becomes a stream through its spliterator
int sum = StreamSupport.stream(range.spliterator(), false)
.mapToInt(Integer::intValue).sum();
System.out.println("stream sum: " + sum);
}
}
Output:
for-each: 4 6 8 10
independent: a.next()=8, b.next()=4
forEachRemaining: 10
remove(): UnsupportedOperationException (default method)
stream sum: 28
- The iterator keeps only the next value, so the range uses the same memory whether it has five elements or five billion.
- Each call to
returns a new, independent iterator. Afteriterator() had moved past 4 and 6,a still started at 4.b throwsnext() past the end, as the contract requires.NoSuchElementException hands the remaining elements, here only 10, to a lambda.forEachRemaining is a default method that throwsremove() ; read-only iterators simply do not override it.UnsupportedOperationException also provides a defaultIterable , sospliterator() turns the range into a stream, summing 4 + 6 + 8 + 10 = 28.StreamSupport.stream
Enumeration and iterating maps
Older APIs such as VectorHashtableEnumeration
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
public class LegacyAndMaps {
public static void main(String[] args) {
// Enumeration: the Java 1.0 predecessor of Iterator, still returned by some APIs
Vector<String> legacy = new Vector<>(java.util.List.of("x", "y", "z"));
Enumeration<String> e = legacy.elements();
StringBuilder sb = new StringBuilder();
while (e.hasMoreElements()) {
sb.append(e.nextElement());
}
System.out.println("Enumeration: " + sb);
// Java 9: Enumeration.asIterator() adapts it to an Iterator
Iterator<String> it = legacy.elements().asIterator();
it.next();
System.out.println("asIterator: next is " + it.next());
// Maps are not Iterable; iterate one of their views
Map<String, Integer> stock = new TreeMap<>(Map.of("apple", 5, "fig", 0, "kiwi", 8));
Iterator<Map.Entry<String, Integer>> entries = stock.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, Integer> en = entries.next();
if (en.getValue() == 0) {
entries.remove(); // removes the entry from the map
} else {
en.setValue(en.getValue() * 10); // writes through to the map
}
}
System.out.println("map after iterator edits: " + stock);
// There is no ListIterator for maps or sets: only lists have positions
System.out.println("listIterator on a list only; TreeMap navigation uses keys instead: "
+ ((TreeMap<String, Integer>) stock).descendingKeySet());
}
}
Output:
Enumeration: xyz
asIterator: next is y
map after iterator edits: {apple=50, kiwi=80}
listIterator on a list only; TreeMap navigation uses keys instead: [kiwi, apple]
, from Java 1.0, hasEnumeration andhasMoreElements and no removal. Java 9 addednextElement , which adapts it to anasIterator() for newer code.Iterator- A
is notMap . ItsIterable iterator can remove entries, which removedentrySet() from the map, andfig writes through to the map.Entry.setValue - Sets and maps have no positions, so they offer no
. Sorted ones provide their own navigation instead, such asListIterator on adescendingKeySet() ; seeTreeMapNavigableMap and NavigableSet .
All the ways to loop over maps are compared on
Fail-fast and weakly consistent iterators
An iterator walks a collection that someone else may change at the same time. The standard collections in java.utilmodCountnext()
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
public class FailFastAndConcurrent {
public static void main(String[] args) {
// 1. Fail-fast: changing the list behind the iterator's back is detected
List<String> list = new ArrayList<>(List.of("a", "b", "c", "d"));
try {
for (String s : list) {
if (s.equals("a")) {
list.remove("a");
}
}
} catch (ConcurrentModificationException e) {
System.out.println("remove(\"a\") during for-each: ConcurrentModificationException");
}
// 2. ...but not always: removing the second-to-last element ends the loop silently
List<String> quiet = new ArrayList<>(List.of("a", "b", "c", "d"));
List<String> seen = new ArrayList<>();
for (String s : quiet) {
seen.add(s);
if (s.equals("c")) {
quiet.remove("c"); // size drops to 3, hasNext() is false
}
}
System.out.println("remove(\"c\") during for-each: no exception, visited " + seen
+ ", d was never visited");
// 3. CopyOnWriteArrayList: the iterator works on a snapshot
List<String> cow = new CopyOnWriteArrayList<>(List.of("a", "b", "c"));
Iterator<String> it = cow.iterator();
cow.add("d");
StringBuilder snapshot = new StringBuilder();
it.forEachRemaining(snapshot::append);
System.out.println("CopyOnWriteArrayList iterator saw " + snapshot + ", list is " + cow);
try {
cow.iterator().remove();
} catch (UnsupportedOperationException | IllegalStateException e) {
System.out.println("snapshot iterator remove(): " + e.getClass().getSimpleName());
}
// 4. ConcurrentHashMap: weakly consistent, never throws, may or may not see changes
Map<Integer, String> chm = new ConcurrentHashMap<>(Map.of(1, "a", 2, "b", 3, "c"));
int visited = 0;
for (Integer key : chm.keySet()) {
chm.remove(key); // allowed while iterating
visited++;
}
System.out.println("ConcurrentHashMap: removed during iteration, visited " + visited
+ ", map now " + chm);
}
}
Output:
remove("a") during for-each: ConcurrentModificationException
remove("c") during for-each: no exception, visited [a, b, c], d was never visited
CopyOnWriteArrayList iterator saw abc, list is [a, b, c, d]
snapshot iterator remove(): UnsupportedOperationException
ConcurrentHashMap: removed during iteration, visited 3, map now {}
- Removing "a" through the list, not the iterator, made the next
thrownext() . Despite the name, no second thread is involved: the "concurrent" modification came from the same loop.ConcurrentModificationException - Removing "c", the second-to-last element, did not throw. The list shrank to 3, the cursor was at 3, so
returnedhasNext() and the loop ended before the check infalse could run. "d" was silently skipped. Fail-fast behavior is a best-effort bug detector, not a guarantee, which is why code must not rely on catching the exception.next() - A
iterator walks the array that existed when it was created: it saw "abc" although "d" had been added, and it never throws. It also cannot remove;CopyOnWriteArrayList threwremove() .UnsupportedOperationException iterators are weakly consistent: removing entries while iterating is allowed, never throws, and each entry is returned at most once; changes made during the iteration may or may not be seen. All three keys were visited and the map ended empty.ConcurrentHashMap
To remove elements safely from an ordinary list, use Iterator.remove()ListIteratorremoveIf
Spliterator: the iterator behind streams
Java 8 added SpliteratorIteratorSIZEDORDEREDIterable
import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
public class SpliteratorBasics {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(IntStream.rangeClosed(1, 8).boxed().toList());
Spliterator<Integer> whole = numbers.spliterator();
System.out.println("estimated size: " + whole.estimateSize()
+ ", SIZED: " + whole.hasCharacteristics(Spliterator.SIZED)
+ ", ORDERED: " + whole.hasCharacteristics(Spliterator.ORDERED));
// trySplit hands the first part to a new spliterator: how parallel streams divide work
Spliterator<Integer> firstHalf = whole.trySplit();
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
firstHalf.forEachRemaining(n -> a.append(n).append(' '));
whole.forEachRemaining(n -> b.append(n).append(' '));
System.out.println("after trySplit: first part " + a + "| rest " + b);
// tryAdvance: one element at a time, returns false at the end
Spliterator<Integer> one = List.of(10, 20).spliterator();
while (one.tryAdvance(n -> System.out.print("tryAdvance " + n + " "))) {
// the action has already run
}
System.out.println();
// Any Iterable can become a stream through its spliterator
Iterable<String> words = List.of("iterator", "spliterator", "stream");
long longWords = StreamSupport.stream(words.spliterator(), false)
.filter(w -> w.length() > 6).count();
System.out.println("words longer than 6 letters: " + longWords);
}
}
Output:
estimated size: 8, SIZED: true, ORDERED: true
after trySplit: first part 1 2 3 4 | rest 5 6 7 8
tryAdvance 10 tryAdvance 20
words longer than 6 letters: 2
- An
spliterator knows its exact size (8) and keeps the list's order, so a stream over it can skip size calculations and preserve order.ArrayList handed the first half, 1 to 4, to a new spliterator and kept 5 to 8. A parallel stream repeats this until the pieces are small enough, then processes them on the common fork-join pool. Collections that split evenly (arrays,trySplit() ) parallelize well;ArrayList and mostLinkedList s split poorly.Iterable combinestryAdvance andhasNext : it runs the action on the next element and returnsnext when there is none, which avoids the two-call protocol offalse .Iterator makes a stream from anyStreamSupport.stream(iterable.spliterator(), false) , including your own;Iterable has a defaultIterable built on its iterator; thespliterator()streams page covers what happens next.
Index loop or iterator: the cost on each list type
A loop with get(i)ArrayListLinkedListget(i)
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class IndexVsIterator {
static long byIndex(List<Integer> list) {
long sum = 0;
for (int i = 0; i < list.size(); i++) {
sum += list.get(i);
}
return sum;
}
static long byIterator(List<Integer> list) {
long sum = 0;
for (Iterator<Integer> it = list.iterator(); it.hasNext();) {
sum += it.next();
}
return sum;
}
interface Job {
long run();
}
static void time(String name, Job job) {
long best = Long.MAX_VALUE;
long result = 0;
for (int i = 0; i < 3; i++) {
long t = System.nanoTime();
result = job.run();
best = Math.min(best, System.nanoTime() - t);
}
System.out.printf("%-30s %8.2f ms (sum %d)%n", name, best / 1e6, result);
}
public static void main(String[] args) {
int n = 50000;
List<Integer> array = new ArrayList<>();
for (int i = 0; i < n; i++) {
array.add(i);
}
List<Integer> linked = new LinkedList<>(array);
time("ArrayList, get(i) loop", () -> byIndex(array));
time("ArrayList, iterator", () -> byIterator(array));
time("LinkedList, iterator", () -> byIterator(linked));
time("LinkedList, get(i) loop", () -> byIndex(linked));
}
}
Output (rough timings on a shared 2-CPU machine):
ArrayList, get(i) loop 0.31 ms (sum 1249975000)
ArrayList, iterator 1.91 ms (sum 1249975000)
LinkedList, iterator 0.47 ms (sum 1249975000)
LinkedList, get(i) loop 852.94 ms (sum 1249975000)
- On the
, both loops took well under a few milliseconds:ArrayList is a direct array access. On this busy machine the iterator version was occasionally slower in a single run, but the difference is noise.get(i) - On the
, the iterator was just as fast, because it keeps its place and follows one link per step. TheLinkedList loop took hundreds of milliseconds: each call walks up to 25,000 nodes, so the whole loop does about 625 million steps, a cost that grows with the square of the list size.get(i) - For-each loops use the iterator, so they are always safe. Code that takes a
parameter and loops withList can become very slow when a caller passes aget(i) ; checkLinkedList or simply use for-each.list instanceof RandomAccess
Which one to use
| Task | Use |
|---|---|
| Read every element | A for-each loop |
| Remove some elements while looping | Iterator.remove()removeIf |
| Replace elements while looping | ListIterator.setreplaceAll |
| Insert while looping | ListIterator.add |
| Walk a list backwards | list.reversed()listIterator(size())previous() |
| Know the index while iterating | nextIndex()ArrayList |
| Make a class usable in for-each | Implement Iterable<T> |
Old API returns Enumeration | asIterator()Collections.list(e) |