Skip to main content
HashMap internals · Topic 6 of 6

Iteration order and fail-fast

Definition​

A HashMap does not promise any iteration order, so never depend on it. It is also fail-fast: changing the map while looping over it throws ConcurrentModificationException. Remove entries with an iterator or removeIf.

Example code​

Removing entries safely while iterating

import java.util.HashMap;
import java.util.Map;

class Demo {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>(Map.of("apple", 5, "pear", 0, "fig", 0, "plum", 3));

try {
for (String key : stock.keySet()) {
if (stock.get(key) == 0) stock.remove(key); // wrong: changes the map while looping
}
} catch (java.util.ConcurrentModificationException e) {
System.out.println("fail-fast: ConcurrentModificationException");
}

stock.entrySet().removeIf(entry -> entry.getValue() == 0); // right: remove through the entry set
System.out.println(new java.util.TreeMap<>(stock)); // sorted copy, so the output is stable
}
}

// Output:
// fail-fast: ConcurrentModificationException
// {apple=5, plum=3}

Finished this page? Track your progress (saved only in your browser).