Iterator vs ListIterator

Collections · lesson 20 of 42 · 3 min read

Walk a collection by hand when for-each is not enough, forwards or backwards.

Open this lesson in the learning hub

Key points

  • Every Iterable hands out an Iterator: hasNext, next, and a safe remove.
  • A for-each loop is an iterator. The compiler writes those same three calls for you.
  • ListIterator exists on lists only. It adds previous, set, add, and index access.
  • set replaces the element you just returned. add inserts before the cursor, so the walk skips it.
  • To go backwards start at list.listIterator(list.size()) and loop while hasPrevious().
  • Call next() before remove() or you get an IllegalStateException.

Example

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("ann", "bob", "cyd", "dee"));

        Iterator<String> it = names.iterator();
        while (it.hasNext()) {
            if (it.next().startsWith("b")) it.remove();
        }
        System.out.println("Iterator.remove   : " + names);

        ListIterator<String> li = names.listIterator();
        while (li.hasNext()) {
            int i = li.nextIndex();
            String v = li.next();
            li.set(i + ":" + v.toUpperCase());
        }
        System.out.println("ListIterator.set  : " + names);

        li = names.listIterator();
        li.next();
        li.add("inserted");
        System.out.println("ListIterator.add  : " + names);

        StringBuilder backwards = new StringBuilder();
        ListIterator<String> rev = names.listIterator(names.size());
        while (rev.hasPrevious()) backwards.append(rev.previous()).append(" ");
        System.out.println("hasPrevious walk  : " + backwards.toString().trim());

        System.out.println("Iterator gives you: hasNext, next, remove");
        System.out.println("ListIterator adds : set, add, previous, indexes - lists only");
    }
}

Iterator for any collection, ListIterator when you need to look back or edit in place.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.