Loop Through a Map

A Map is not Iterable, so every loop over it goes through one of its views: entrySet for keys and values together, keySet for keys, or values. Java 8 added forEach and streams on top. This page runs each style, explains the order each map type gives, shows what you may and may not change while looping, and measures why keySet plus get is the slow choice.

Contents

Maps are looped through their views

Map does not extend Iterable, because it holds pairs rather than single elements. Instead it offers three views: entrySet() of Map.Entry objects, keySet() and values(). Looping over a view walks the map's own internal structure, the bucket array of a HashMap or the tree of a TreeMap, and the entries handed out are the map's real entries, not copies.

Two consequences matter. The loop order is whatever the map's structure gives, and each map type gives a different one. And looking up each key again with get inside a keySet loop repeats work the loop has already done.

Ways to loop through a map
StyleSinceGives youBest for
for (Map.Entry<K, V> e : map.entrySet())Java 5Key and valueMost loops; changing values with setValue
map.forEach((k, v) -> ...)Java 8Key and value in a lambdaShort actions
for (K k : map.keySet())Java 5Keys onlyWhen values are not needed
for (V v : map.values())Java 5Values onlyTotals and checks over values
map.entrySet().iterator()Java 1.2Entries with safe removeRemoving while looping
map.entrySet().stream()Java 8A pipeline over entriesFiltering, sorting, collecting
map.replaceAll((k, v) -> ...)Java 8Every value replacedTransforming all values

Each example is a complete program, run on JDK 21.

The loop styles

A small map of exam scores is looped over in each style, then curved, filtered and searched, so the output shows both reading and changing the map.

Java
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class MapLoops {

    public static void main(String[] args) {
        Map<String, Integer> scores = new LinkedHashMap<>();   // predictable order for the demo
        scores.put("ann", 82);
        scores.put("bob", 67);
        scores.put("cy", 91);

        // 1. entrySet: key and value together (the usual choice)
        for (Map.Entry<String, Integer> e : scores.entrySet()) {
            System.out.println("entrySet: " + e.getKey() + " = " + e.getValue());
        }

        // 2. forEach with a two-argument lambda
        scores.forEach((name, score) ->
                System.out.println("forEach:  " + name + " = " + score));

        // 3. keys only, values only
        System.out.println("keySet:   " + String.join(", ", scores.keySet()));
        int total = 0;
        for (int s : scores.values()) {
            total += s;
        }
        System.out.println("values:   total " + total);

        // 4. Changing values while looping: Entry.setValue is allowed
        for (Map.Entry<String, Integer> e : scores.entrySet()) {
            e.setValue(e.getValue() + 5);
        }
        System.out.println("curved:   " + scores);

        // 5. Removing while looping: use the entry iterator
        Iterator<Map.Entry<String, Integer>> it = scores.entrySet().iterator();
        while (it.hasNext()) {
            if (it.next().getValue() < 80) {
                it.remove();
            }
        }
        System.out.println("passed:   " + scores);

        // 6. A stream over the entries
        scores.entrySet().stream()
                .filter(e -> e.getValue() > 90)
                .forEach(e -> System.out.println("stream:   " + e.getKey() + " scored over 90"));
    }
}

Output:

Output
entrySet: ann = 82
entrySet: bob = 67
entrySet: cy = 91
forEach:  ann = 82
forEach:  bob = 67
forEach:  cy = 91
keySet:   ann, bob, cy
values:   total 240
curved:   {ann=87, bob=72, cy=96}
passed:   {ann=87, cy=96}
stream:   cy scored over 90
  • The entrySet loop and forEach both receive the key and the value together, and are the two standard ways to loop over a map.
  • keySet() and values() are for loops that need only one side, such as joining the names or totalling the scores.
  • replaceAll applied the curve to every value in place; a filtered copy kept only the passing scores.
  • A stream over entrySet() filters and acts on entries, here reporting the score above 90. Streams over maps are covered in more detail on converting a map to a list.

Iteration order, and changes during a loop

The same four names go into a HashMap, a LinkedHashMap and a TreeMap, inserted in a deliberately unsorted order. The second half changes a map while looping over it, in allowed and forbidden ways.

Java
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class OrderAndChanges {

    public static void main(String[] args) {
        List<String> names = List.of("zoe", "ann", "max", "bob");

        // The map type decides the loop order
        Map<String, Integer> hash = new HashMap<>();
        LinkedHashMap<String, Integer> linked = new LinkedHashMap<>();
        TreeMap<String, Integer> tree = new TreeMap<>();
        for (String n : names) {
            hash.put(n, n.length());
            linked.put(n, n.length());
            tree.put(n, n.length());
        }
        System.out.println("HashMap:            " + hash.keySet());
        System.out.println("LinkedHashMap:      " + linked.keySet() + " (insertion order)");
        System.out.println("TreeMap:            " + tree.keySet() + " (sorted)");
        System.out.println("TreeMap descending: " + tree.descendingMap().keySet());
        System.out.println("reversed() view:    " + linked.sequencedKeySet().reversed()
            + " (Java 21)");

        // Changing values while looping is allowed; adding keys is not
        Map<String, Integer> scores = new TreeMap<>(Map.of("ann", 82, "bob", 67));
        for (Map.Entry<String, Integer> e : scores.entrySet()) {
            e.setValue(e.getValue() + 1);              // writes through to the map
        }
        System.out.println("after setValue:     " + scores);
        scores.replaceAll((k, v) -> v * 10);
        System.out.println("after replaceAll:   " + scores);
        try {
            for (String k : scores.keySet()) {
                scores.put(k + "2", 0);                // structural change
            }
        } catch (ConcurrentModificationException e) {
            System.out.println("put a new key in the loop: ConcurrentModificationException");
        }
        // put on an EXISTING key is not a structural change
        for (String k : List.copyOf(scores.keySet())) {
            scores.put(k, 1);
        }
        System.out.println("put on existing keys: " + scores);
    }
}

Output:

Output
HashMap:            [ann, zoe, bob, max]
LinkedHashMap:      [zoe, ann, max, bob] (insertion order)
TreeMap:            [ann, bob, max, zoe] (sorted)
TreeMap descending: [zoe, max, bob, ann]
reversed() view:    [bob, max, ann, zoe] (Java 21)
after setValue:     {ann=83, bob=68}
after replaceAll:   {ann=830, bob=680}
put a new key in the loop: ConcurrentModificationException
put on existing keys: {ann=1, ann2=1, bob=1}
  • The HashMap order, ann, zoe, bob, max, comes from the hash codes and the table size, matches neither insertion nor sorting, and can change when the map grows. Never rely on it.
  • LinkedHashMap loops in insertion order and TreeMap in sorted key order; descendingMap() reverses a TreeMap, and Java 21's sequencedKeySet().reversed() reverses a LinkedHashMap. See TreeMap and LinkedHashMap.
  • Map.Entry.setValue during an entrySet loop writes the new value into the map, and replaceAll does the same for every entry. Changing values is not a structural change, so it is safe.
  • Adding a new key during the loop is structural, and the next step threw ConcurrentModificationException. Worse, the exception came after the change, so ann2 had already been added: a failed loop can leave the map half-modified.
  • put on keys that already exist is not structural. Looping over a copy of the key set, as the last loop does, is the simple way to make arbitrary changes. To remove entries, see removing entries from a map.

Nested maps, counters, removal and concurrent maps

Four practical situations: a map whose values are lists, numbering the entries, removing during the loop, and a map that other threads may change while it is being looped over.

Java
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class NestedAndConcurrent {

    public static void main(String[] args) {
        // A map of lists: a loop inside a loop
        Map<String, List<String>> teams = new TreeMap<>(Map.of(
            "blue", List.of("cy"), "red", List.of("ann", "bo")));
        for (Map.Entry<String, List<String>> team : teams.entrySet()) {
            for (String member : team.getValue()) {
                System.out.println(team.getKey() + " -> " + member);
            }
        }

        // Numbering entries while looping: a counter outside the loop
        int i = 1;
        for (String key : teams.keySet()) {
            System.out.println(i++ + ". " + key);
        }

        // Iterator over entries: remove safely while looping
        Map<String, Integer> stock = new TreeMap<>(Map.of("apple", 5, "fig", 0, "kiwi", 8));
        Iterator<Map.Entry<String, Integer>> it = stock.entrySet().iterator();
        while (it.hasNext()) {
            if (it.next().getValue() == 0) {
                it.remove();
            }
        }
        System.out.println("after iterator.remove: " + stock);

        // ConcurrentHashMap: adding during the loop is allowed (weakly consistent)
        Map<String, Integer> live = new ConcurrentHashMap<>(Map.of("a", 1, "b", 2));
        for (String k : live.keySet()) {
            live.putIfAbsent(k + k, 0);
        }
        System.out.println("ConcurrentHashMap after adding in the loop: " + live.size()
            + " entries, no exception");

        // A one-line report from a map
        System.out.println(teams.entrySet().stream()
            .map(e -> e.getKey() + "=" + e.getValue().size())
            .collect(Collectors.joining(", ", "team sizes: ", "")));
    }
}

Output:

Output
blue -> cy
red -> ann
red -> bo
1. blue
2. red
after iterator.remove: {apple=5, kiwi=8}
ConcurrentHashMap after adding in the loop: 4 entries, no exception
team sizes: blue=1, red=2
  • A map of lists needs a loop inside a loop: the outer one over entries, the inner one over each entry's list. flatMap does the same in a stream; see the flatMap page.
  • Maps have no index, so numbering entries needs a counter variable outside the loop. In a forEach lambda that counter would have to be an AtomicInteger or an array.
  • An explicit iterator over entrySet() removes entries safely, here the zero stock for fig.
  • A ConcurrentHashMap allows changes during a loop: the iterator is weakly consistent and never throws ConcurrentModificationException, though it may or may not see the new keys. See the ConcurrentHashMap page.
  • Mapping entries to strings and joining them builds a one-line report.

Why keySet plus get is slower

A common pattern loops over the keys and calls get(key) for each value. The program compares it with entrySet and forEach on a HashMap and a TreeMap of a million entries, keeping the fastest of three runs.

Java
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class KeySetCost {

    static long viaKeySet(Map<Integer, Integer> map) {
        long sum = 0;
        for (Integer k : map.keySet()) {
            sum += map.get(k);                 // a second lookup for every key
        }
        return sum;
    }

    static long viaEntrySet(Map<Integer, Integer> map) {
        long sum = 0;
        for (Map.Entry<Integer, Integer> e : map.entrySet()) {
            sum += e.getValue();               // the value comes with the entry
        }
        return sum;
    }

    static long viaForEach(Map<Integer, Integer> map) {
        long[] sum = {0};
        map.forEach((k, v) -> sum[0] += v);
        return sum[0];
    }

    interface Loop {
        long run(Map<Integer, Integer> m);
    }

    // Best of 3 runs, in milliseconds
    static double best(Map<Integer, Integer> m, Loop loop) {
        long best = Long.MAX_VALUE;
        for (int r = 0; r < 3; r++) {
            long t0 = System.nanoTime();
            if (loop.run(m) < 0) {
                throw new AssertionError();
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        return best / 1e6;
    }

    public static void main(String[] args) {
        Map<Integer, Integer> hash = new HashMap<>();
        Map<Integer, Integer> tree = new TreeMap<>();
        for (int i = 0; i < 1000000; i++) {
            hash.put(i, i);
            tree.put(i, i);
        }
        for (String name : new String[] {"HashMap", "TreeMap"}) {
            Map<Integer, Integer> m = name.equals("HashMap") ? hash : tree;
            System.out.printf("%s: keySet + get %5.1f ms, entrySet %5.1f ms, forEach %5.1f ms%n",
                name, best(m, KeySetCost::viaKeySet), best(m, KeySetCost::viaEntrySet),
                best(m, KeySetCost::viaForEach));
        }
    }
}

Output (approximate, from a 2-CPU Linux machine running JDK 21):

Output
HashMap: keySet + get  12.2 ms, entrySet  10.2 ms, forEach  10.4 ms
TreeMap: keySet + get  77.4 ms, entrySet  18.2 ms, forEach  21.1 ms
  • For a HashMap, keySet plus get was slower than entrySet, by anything from a little to about half again across runs, because every get hashes the key and searches its bucket again.
  • For a TreeMap, each get is a tree search of about 20 comparisons, so the keySet loop was several times slower than entrySet.
  • forEach was close to entrySet for both maps. Both walk the structure once and receive key and value together.

The views write through, and entries are live

keySet(), values() and entrySet() are not copies. They are views backed by the map, and the entries they hand out are usually the map's own internal nodes. That makes some changes easy, and makes holding on to entries after a loop risky.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class ViewsAndEntries {

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

        // 1. The views write through: removing from a view removes from the map
        stock.keySet().remove("kiwi");
        stock.values().remove(0);                     // removes only the first entry with 0
        System.out.println("after keySet().remove and values().remove(0): " + stock);
        stock.values().removeIf(v -> v == 0);
        System.out.println("after values().removeIf(v == 0):            " + stock);
        try {
            stock.keySet().add("plum");
        } catch (UnsupportedOperationException e) {
            System.out.println("keySet().add: UnsupportedOperationException (no value to add)");
        }

        // 2. Entries kept after the loop are live nodes, not copies
        Map<String, Integer> scores = new HashMap<>(Map.of("ann", 70, "bob", 80));
        List<Map.Entry<String, Integer>> saved = new ArrayList<>(scores.entrySet());
        scores.put("ann", 99);
        System.out.println("saved entry after put(ann, 99): " + find(saved, "ann"));
        List<Map.Entry<String, Integer>> copies = scores.entrySet().stream()
            .map(Map.Entry::copyOf).toList();
        scores.put("ann", 1);
        System.out.println("Map.Entry.copyOf snapshot after put(ann, 1): " + find(copies, "ann")
            + ", map now " + scores.get("ann"));

        // 3. A saved entry from a removed key keeps its old value and changes nothing
        Map.Entry<String, Integer> bob = find(saved, "bob");
        scores.remove("bob");
        bob.setValue(5);
        System.out.println("setValue on a removed entry: entry " + bob + ", map " + scores);
    }

    static Map.Entry<String, Integer> find(List<Map.Entry<String, Integer>> list, String key) {
        return list.stream().filter(e -> e.getKey().equals(key)).findFirst().orElseThrow();
    }
}
Output
after keySet().remove and values().remove(0): {apple=5, pear=0}
after values().removeIf(v == 0):            {apple=5}
keySet().add: UnsupportedOperationException (no value to add)
saved entry after put(ann, 99): ann=99
Map.Entry.copyOf snapshot after put(ann, 1): ann=99, map now 1
setValue on a removed entry: entry bob=5, map {ann=1}
  • keySet().remove("kiwi") removed the whole entry from the map, and values().remove(0) removed only the first entry whose value was 0, fig, leaving pear=0 behind. values().removeIf(v -> v == 0) removed every remaining match.
  • keySet().add threw UnsupportedOperationException, because a key added through the view would have no value. None of the three views supports adding.
  • An entry saved from a HashMap loop showed ann=99 after a later put. It is the map's node, so it follows the map.
  • Map.Entry.copyOf (Java 17) made snapshots that kept ann=99 while the map moved on to 1. Use it when entries must outlive the loop, for example in a list that is sorted or returned.
  • After bob was removed, setValue(5) on its saved entry succeeded, but changed only the detached node. The map stayed {ann=1}, and nothing reported the lost write.

A HashMap loop costs its capacity, not its size

A HashMap iterator walks the whole bucket array and skips empty slots, so a loop takes time in proportion to the table's capacity plus its size. The table grows as entries are added and never shrinks. The program loops 100 times over five maps that all hold the same 100 entries but have very different tables, after a warm-up round.

Java
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class CapacityCost {

    public static void main(String[] args) {
        Map<Integer, Integer> fresh = new HashMap<>();
        Map<Integer, Integer> shrunk = new HashMap<>();
        Map<Integer, Integer> linkedShrunk = new LinkedHashMap<>();
        Map<Integer, Integer> presized = new HashMap<>(2000000);
        for (int i = 0; i < 1000000; i++) {
            shrunk.put(i, i);
            linkedShrunk.put(i, i);
        }
        // Remove all but 100 entries; the bucket arrays stay large
        shrunk.keySet().removeIf(k -> k >= 100);
        linkedShrunk.keySet().removeIf(k -> k >= 100);
        for (int i = 0; i < 100; i++) {
            fresh.put(i, i);
            presized.put(i, i);
        }
        System.out.println("100 loops over maps that each hold 100 entries (best of 3):");
        for (int round = 0; round < 2; round++) {
            boolean print = round == 1;
            time("HashMap, shrunk from 1,000,000", shrunk, print);
            time("HashMap, new HashMap<>(2_000_000)", presized, print);
            time("LinkedHashMap, shrunk from 1,000,000", linkedShrunk, print);
            time("new HashMap<>(shrunk) copy", new HashMap<>(shrunk), print);
            time("HashMap, built with 100", fresh, print);
        }
    }

    static void time(String name, Map<Integer, Integer> map, boolean print) {
        long best = Long.MAX_VALUE;
        long sum = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            for (int rep = 0; rep < 100; rep++) {
                for (Map.Entry<Integer, Integer> e : map.entrySet()) {
                    sum += e.getValue();
                }
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        if (print) {
            System.out.printf("  %-38s %8.2f ms  (checksum %d)%n", name, best / 1e6, sum);
        }
    }
}

Output (best of 3 runs, rough timings from a 2-CPU Linux machine on JDK 21):

Output
100 loops over maps that each hold 100 entries (best of 3):
  HashMap, shrunk from 1,000,000           204.93 ms  (checksum 1485000)
  HashMap, new HashMap<>(2_000_000)        209.37 ms  (checksum 1485000)
  LinkedHashMap, shrunk from 1,000,000       0.06 ms  (checksum 1485000)
  new HashMap<>(shrunk) copy                 0.11 ms  (checksum 1485000)
  HashMap, built with 100                    0.12 ms  (checksum 1485000)
  • The HashMap that once held a million entries took hundreds to thousands of times longer to loop over than one built with 100, though both now hold 100. Its table still has 2,097,152 slots, of which 100 are in use, and the iterator checks every one of them on each pass. The removeIf that shrank it gave no hint of this, and size() reported a normal 100.
  • A HashMap created with an initial capacity of 2,000,000 was just as slow, because the constructor's capacity is allocated at the first put. Oversizing a map "to be safe" makes every loop over it slower.
  • The LinkedHashMap shrunk the same way stayed fast. Its iterator follows the linked list through the live entries and never visits the table.
  • Copying the shrunk map with new HashMap<>(shrunk) produced a table sized for 100 entries and restored the speed. That copy is the way to reclaim a table that has grown far beyond the data.

The HashMap documentation says the same: iteration time is proportional to the capacity plus the number of mappings, so it advises against setting the initial capacity too high when iteration performance matters.

Which loop to use

Choosing a map loop
You needUse
Keys and valuesentrySet() loop or forEach((k, v) -> ...)
Keys onlykeySet()
Values onlyvalues()
Change every valuereplaceAll
Change some valuesentry.setValue in an entrySet loop
Remove entriesentrySet().removeIf or the iterator's remove
Add keys based on existing onesLoop over a copy, or collect changes and apply them after
A predictable orderLinkedHashMap or TreeMap
Filter, sort or collectentrySet().stream()
NeverkeySet() plus get when both are needed

For looping over lists, see looping through a list.