TExcelTAD
Home › Java › Java Iterator

Java Iterator

An iterator is an object that walks through a collection one element at a time. Every collection in java.util — lists, sets, the views of a map — can hand you an Iterator. In fact, the for-each loop is just a convenient shorthand that uses an iterator behind the scenes.

The Iterator methods

Method Description
hasNext() true if there are more elements
next() returns the next element and moves forward
remove() removes the element last returned by next() (optional operation)
java · try it yourself
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class Main {
    public static void main(String[] args) {
        List<String> cities = new ArrayList<>(List.of("Oslo", "Lima", "Cairo"));
        Iterator<String> it = cities.iterator();
        while (it.hasNext()) {
            String city = it.next();
            System.out.println(city + " (" + city.length() + ")");
        }
    }
}
Oslo (4)
Lima (4)
Cairo (5)

Calling next() when hasNext() is false throws a NoSuchElementException, so always check first.

Removing elements safely

Why use an iterator when for-each is shorter? Because you cannot remove elements from a collection while looping over it with for-each — Java detects the change and throws a ConcurrentModificationException:

java · try it yourself
import java.util.ArrayList;
import java.util.List;

class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(3, 8, 12, 5, 6));
        try {
            for (Integer n : nums) {
                if (n % 2 == 0) {
                    nums.remove(n);       // modifies the list during the loop
                }
            }
        } catch (java.util.ConcurrentModificationException e) {
            System.out.println("ConcurrentModificationException!");
        }
    }
}
ConcurrentModificationException!

The iterator's own remove() method is the safe way:

java · try it yourself
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(3, 8, 12, 5, 6));
        Iterator<Integer> it = nums.iterator();
        while (it.hasNext()) {
            if (it.next() % 2 == 0) {
                it.remove();              // removes the element just returned
            }
        }
        System.out.println(nums);

        // Since Java 8 there's an even shorter way:
        List<Integer> more = new ArrayList<>(List.of(10, 15, 20, 25));
        more.removeIf(n -> n > 18);
        System.out.println(more);
    }
}
[3, 5]
[10, 15]

Iterating over a map

Maps aren't collections themselves, but their keySet(), values() and entrySet() views are, so you can iterate them — and remove entries — with an iterator:

java · try it yourself
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new TreeMap<>(Map.of(
            "pens", 0, "paper", 300, "staples", 0, "folders", 42));

        Iterator<Map.Entry<String, Integer>> it = stock.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Integer> e = it.next();
            if (e.getValue() == 0) {
                System.out.println("Removing sold-out item: " + e.getKey());
                it.remove();
            }
        }
        System.out.println(stock);
    }
}
Removing sold-out item: pens
Removing sold-out item: staples
{folders=42, paper=300}

ListIterator: both directions

Lists also offer a ListIterator, which can move backwards, report indexes and replace elements with set:

java · try it yourself
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

class Main {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>(List.of("alpha", "beta", "gamma"));
        ListIterator<String> it = words.listIterator();
        while (it.hasNext()) {
            int i = it.nextIndex();
            String w = it.next();
            it.set(i + ":" + w.toUpperCase());
        }
        System.out.println(words);

        while (it.hasPrevious()) {       // walk back to the start
            System.out.print(it.previous() + " ");
        }
        System.out.println();
    }
}
[0:ALPHA, 1:BETA, 2:GAMMA]
2:GAMMA 1:BETA 0:ALPHA 

Making your own class iterable

Any class that implements Iterable<T> (one method: iterator()) can be used in a for-each loop:

java · try it yourself
import java.util.Iterator;

class Countdown implements Iterable<Integer> {
    private final int start;

    Countdown(int start) { this.start = start; }

    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<>() {
            private int current = start;
            public boolean hasNext() { return current > 0; }
            public Integer next() { return current--; }
        };
    }
}

class Main {
    public static void main(String[] args) {
        for (int n : new Countdown(5)) {
            System.out.print(n + " ");
        }
        System.out.println("Liftoff!");
    }
}
5 4 3 2 1 Liftoff!

Tip: Use for-each for plain reading, removeIf for simple filtering, and an explicit Iterator when you need to remove or replace elements based on more complex logic.

Test yourself

Which method checks whether an iterator has more elements?

  1. next()
  2. hasNext()
  3. isEmpty()
  4. more()

What happens if you call list.remove(x) inside a for-each loop over the same list?

  1. It works fine
  2. The element is skipped silently
  3. A ConcurrentModificationException is usually thrown
  4. A compile error

What must a class implement to be usable in a for-each loop?

  1. Iterator
  2. Iterable
  3. Collection
  4. Comparable