CKTIS / Java
Map.entrySet(): iterate over key–value pairs
Use `entrySet()` when you need both the key and its corresponding value on each pass through a loop. The method returns a view of the map, not a copy.
Version: Java SE 21
Syntax
Set<Map.Entry<K, V>> entries = map.entrySet();
for (Map.Entry<K, V> entry : entries) {
K key = entry.getKey();
V value = entry.getValue();
}Map.entrySet names a no-argument instance method of java.util.Map<K, V>. The notation Map.entrySet() refers to the same method with its empty argument list; in code, call it on a map instance as map.entrySet(). It returns a Set<Map.Entry<K, V>> with one entry per mapping.
Map.Entry<K, V> is an interface nested in Map. The shorthand Map.Entry.getKey/getValue refers to two methods: in an enhanced for loop, call entry.getKey() to read the key of type K and entry.getValue() to read the value of type V. No extra map.get(key) lookup is needed. Use keySet() if you only need keys or values() if you only need values.
The set is backed by the map, not a snapshot: changes to the map show up in the view, and removing an entry through the view, where supported, also removes the mapping from the map. add and addAll are not supported. Under the general Map contract, modifying the map during iteration leaves the iteration results undefined, except when using a supported Iterator.remove() on the iterator in use or setValue(...) on an entry returned by that iterator. Do not rely on the behavior of an iterator-returned entry after iteration ends.
entrySet() does not itself sort the entries. Iteration order depends on the map implementation. In the example, new TreeMap<>(counts) creates a separate map with the same mappings in the keys’ natural order. The loop iterates over the view of that copy.
Examples
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Map<String, Long> counts = Stream.of("pear", "apple", "plum", "apple", "kiwi", "banana", "pear")
.collect(Collectors.groupingBy(fruit -> fruit, Collectors.counting()));
Map<String, Long> sorted = new TreeMap<>(counts);
for (Map.Entry<String, Long> entry : sorted.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
}
Result
apple = 2 banana = 1 kiwi = 1 pear = 2 plum = 1
`collect(...)` counts occurrences of each fruit name. Only after it finishes does the code create the `TreeMap` copy and print exactly five lines, one per key, in natural key order.
Related lessons
- Java · Lesson 24 · Advanced · Version: 2
- Java · Lesson 57 · Basic · Version: 2
- Java · Lesson 67 · Basic · Version: 2
- Java · Lesson 39 · Intermediate · Version: 2