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
MapIterableentrySet()Map.EntrykeySet()values()HashMapTreeMap
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 getkeySet
| Style | Since | Gives you | Best for |
|---|---|---|---|
for (Map.Entry<K, V> e : map.entrySet()) | Java 5 | Key and value | Most loops; changing values with setValue |
map.forEach((k, v) -> ...) | Java 8 | Key and value in a lambda | Short actions |
for (K k : map.keySet()) | Java 5 | Keys only | When values are not needed |
for (V v : map.values()) | Java 5 | Values only | Totals and checks over values |
map.entrySet().iterator() | Java 1.2 | Entries with safe remove | Removing while looping |
map.entrySet().stream() | Java 8 | A pipeline over entries | Filtering, sorting, collecting |
map.replaceAll((k, v) -> ...) | Java 8 | Every value replaced | Transforming 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.
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:
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
loop andentrySet both receive the key and the value together, and are the two standard ways to loop over a map.forEach andkeySet() are for loops that need only one side, such as joining the names or totalling the scores.values() applied the curve to every value in place; a filtered copy kept only the passing scores.replaceAll- A stream over
filters and acts on entries, here reporting the score above 90. Streams over maps are covered in more detail onentrySet()converting a map to a list .
Iteration order, and changes during a loop
The same four names go into a HashMapLinkedHashMapTreeMap
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:
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
order,HashMap , 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.ann, zoe, bob, max loops in insertion order andLinkedHashMap in sorted key order;TreeMap reverses adescendingMap() , and Java 21'sTreeMap reverses asequencedKeySet().reversed() . SeeLinkedHashMapTreeMap and LinkedHashMap . during anMap.Entry.setValue loop writes the new value into the map, andentrySet does the same for every entry. Changing values is not a structural change, so it is safe.replaceAll- Adding a new key during the loop is structural, and the next step threw
. Worse, the exception came after the change, soConcurrentModificationException had already been added: a failed loop can leave the map half-modified.ann2 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, seeputremoving 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.
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:
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.
does the same in a stream; see theflatMapflatMap page . - Maps have no index, so numbering entries needs a counter variable outside the loop. In a
lambda that counter would have to be anforEach or an array.AtomicInteger - An explicit iterator over
removes entries safely, here the zero stock forentrySet() .fig - A
allows changes during a loop: the iterator is weakly consistent and never throwsConcurrentHashMap , though it may or may not see the new keys. See theConcurrentModificationExceptionConcurrentHashMap 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)entrySetforEachHashMapTreeMap
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):
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 pluskeySet was slower thanget , by anything from a little to about half again across runs, because everyentrySet hashes the key and searches its bucket again.get - For a
, eachTreeMap is a tree search of about 20 comparisons, so theget loop was several times slower thankeySet .entrySet was close toforEach for both maps. Both walk the structure once and receive key and value together.entrySet
The views write through, and entries are live
keySet()values()entrySet()
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();
}
}
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}
removed the whole entry from the map, andkeySet().remove("kiwi") removed only the first entry whose value was 0,values().remove(0) , leavingfig behind.pear=0 removed every remaining match.values().removeIf(v -> v == 0) threwkeySet().add , because a key added through the view would have no value. None of the three views supports adding.UnsupportedOperationException- An entry saved from a
loop showedHashMap after a laterann=99 . It is the map's node, so it follows the map.put (Java 17) made snapshots that keptMap.Entry.copyOf 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.ann=99- After
was removed,bob on its saved entry succeeded, but changed only the detached node. The map stayedsetValue(5) , and nothing reported the lost write.{ann=1}
A HashMap loop costs its capacity, not its size
A HashMap
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):
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
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. TheHashMap that shrank it gave no hint of this, andremoveIf reported a normal 100.size() - A
created with an initial capacity of 2,000,000 was just as slow, because the constructor's capacity is allocated at the firstHashMap . Oversizing a map "to be safe" makes every loop over it slower.put - The
shrunk the same way stayed fast. Its iterator follows the linked list through the live entries and never visits the table.LinkedHashMap - Copying the shrunk map with
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.new HashMap<>(shrunk)
The HashMap
Which loop to use
| You need | Use |
|---|---|
| Keys and values | entrySet()forEach((k, v) -> ...) |
| Keys only | keySet() |
| Values only | values() |
| Change every value | replaceAll |
| Change some values | entry.setValueentrySet |
| Remove entries | entrySet().removeIfremove |
| Add keys based on existing ones | Loop over a copy, or collect changes and apply them after |
| A predictable order | LinkedHashMapTreeMap |
| Filter, sort or collect | entrySet().stream() |
| Never | keySet()get |
For looping over lists, see