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

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() jumps over the next element and returns it; hasNext() asks whether there is one to jump over. The element most recently jumped over is the "current" element, and remove() or set() act on it.

Iterator (Java 1.2) is the general interface that every Collection provides through iterator(), and it is what a for-each loop uses. ListIterator (Java 1.2) extends it for lists only, because only lists have positions: it can move in both directions and knows the index on each side of the cursor.

Iterator and ListIterator compared
CapabilityIteratorListIterator
Available onEvery CollectionList only, via listIterator()
Move forward: hasNext, nextYesYes
Move backward: hasPrevious, previousNoYes
Positions: nextIndex, previousIndexNoYes
Remove the current elementremove(), optionalremove()
Replace the current elementNoset(e)
Insert at the cursorNoadd(e)
Start in the middleNolistIterator(index)
Process the rest with a lambdaforEachRemaining (Java 8)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 ConcurrentModificationException. Changes made through the iterator, with its own remove, set or add, keep it valid. That is the main reason to use an explicit iterator instead of a for-each loop. The examples were compiled and run with JDK 21.

Iterator basics

A set of tags shows that Iterator works on collections without positions, and a small list shows that for-each is the same thing in shorter form.

Java
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:

Output
tag: go
tag: java
tag: sql
next() past the end: NoSuchElementException
for-each: a
for-each: b
  • The while (it.hasNext()) loop visits every element. A TreeSet returns them in sorted order; a HashSet would use its own order.
  • Calling next() when hasNext() is false throws NoSuchElementException, never returns null.
  • The for-each loop compiles to the same iterator(), hasNext() and next() calls. Write the explicit form only when you need remove(), as on the 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.

Java
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:

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
  • nextIndex() reports where the cursor is. After one was removed, the next element, TWO, also reported index 0, because everything shifted left.
  • set replaced TWO with two in place. add inserted three-and-a-half right after three, before the cursor, so the loop did not visit it and went straight on to FOUR at index 3.
  • listIterator(list.size()) starts with the cursor after the last element, and previous() walks back to the start. Since Java 21, list.reversed() is a simpler way to loop backwards when no editing is needed.

The rules for remove, set and add

remove and set need a current element, and add clears it. The program checks the index methods and then breaks the rule on purpose.

Java
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:

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, nextIndex() is 0 and previousIndex() is -1. After two next() calls the cursor is between b and c, so nextIndex() is 2.
  • previous() returns b again: moving back jumps over the element just returned. Alternating next and previous returns the same element each time.
  • After add, there is no current element, so set threw IllegalStateException. The same happens for remove or set before the first next, and for two remove calls in a row.
  • The inserted X went in at the cursor position, before b.

Writing your own Iterable

Any class that implements Iterable<T> works in a for-each loop. The example is a range of even numbers that computes its elements on demand instead of storing them in a list.

Java
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:

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 iterator() returns a new, independent iterator. After a had moved past 4 and 6, b still started at 4.
  • next() throws NoSuchElementException past the end, as the contract requires.
  • forEachRemaining hands the remaining elements, here only 10, to a lambda.
  • remove() is a default method that throws UnsupportedOperationException; read-only iterators simply do not override it.
  • Iterable also provides a default spliterator(), so StreamSupport.stream turns the range into a stream, summing 4 + 6 + 8 + 10 = 28.

Enumeration and iterating maps

Older APIs such as Vector, Hashtable and servlet request headers still return Enumeration, and maps need a view before they can be iterated. The program covers both.

Java
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:

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]
  • Enumeration, from Java 1.0, has hasMoreElements and nextElement and no removal. Java 9 added asIterator(), which adapts it to an Iterator for newer code.
  • A Map is not Iterable. Its entrySet() iterator can remove entries, which removed fig from the map, and Entry.setValue writes through to the map.
  • Sets and maps have no positions, so they offer no ListIterator. Sorted ones provide their own navigation instead, such as descendingKeySet() on a TreeMap; see NavigableMap and NavigableSet.

All the ways to loop over maps are compared on looping through a map, and over lists on looping through a list.

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.util are fail-fast: they count structural changes (a field called modCount), and the iterator checks the count on every next(). The concurrent collections use different rules. The program changes four collections during iteration and shows what each does.

Java
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:

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 next() throw ConcurrentModificationException. Despite the name, no second thread is involved: the "concurrent" modification came from the same loop.
  • Removing "c", the second-to-last element, did not throw. The list shrank to 3, the cursor was at 3, so hasNext() returned false and the loop ended before the check in next() 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.
  • A CopyOnWriteArrayList 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; remove() threw UnsupportedOperationException.
  • ConcurrentHashMap 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.

To remove elements safely from an ordinary list, use Iterator.remove(), ListIterator or removeIf; the removing elements while iterating page compares them.

Spliterator: the iterator behind streams

Java 8 added Spliterator, a second iteration interface designed for streams. It can do two things an Iterator cannot: report facts about its source (characteristics such as SIZED and ORDERED), and split itself in two so that parallel streams can hand parts of the data to different threads. The program splits a list of 8 numbers, walks a spliterator one element at a time, and turns an Iterable into a stream.

Java
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:

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 ArrayList spliterator knows its exact size (8) and keeps the list's order, so a stream over it can skip size calculations and preserve order.
  • trySplit() 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, ArrayList) parallelize well; LinkedList and most Iterables split poorly.
  • tryAdvance combines hasNext and next: it runs the action on the next element and returns false when there is none, which avoids the two-call protocol of Iterator.
  • StreamSupport.stream(iterable.spliterator(), false) makes a stream from any Iterable, including your own; Iterable has a default spliterator() built on its iterator; the streams page covers what happens next.

Index loop or iterator: the cost on each list type

A loop with get(i) and a loop with an iterator look equivalent, and for an ArrayList they are. For a LinkedList they are not, because get(i) has to walk from one end of the list to position i every time. The program sums 50,000 numbers both ways on both list types, keeping the best of 3 runs.

Java
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):

Output
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 ArrayList, both loops took well under a few milliseconds: get(i) is a direct array access. On this busy machine the iterator version was occasionally slower in a single run, but the difference is noise.
  • On the LinkedList, the iterator was just as fast, because it keeps its place and follows one link per step. The get(i) 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.
  • For-each loops use the iterator, so they are always safe. Code that takes a List parameter and loops with get(i) can become very slow when a caller passes a LinkedList; check list instanceof RandomAccess or simply use for-each.

Which one to use

Choosing an iteration tool
TaskUse
Read every elementA for-each loop
Remove some elements while loopingIterator.remove(), or removeIf without a loop
Replace elements while loopingListIterator.set, or replaceAll
Insert while loopingListIterator.add
Walk a list backwardslist.reversed() (Java 21), or listIterator(size()) with previous()
Know the index while iteratingnextIndex(), or an index loop on an ArrayList
Make a class usable in for-eachImplement Iterable<T>
Old API returns EnumerationasIterator() or Collections.list(e)