What is Map.Entry and how do you use it to iterate over a Map's key-value pairs?
answer
- entrySet() = both key and value in one pass
- keySet()+get() = one extra lookup per key
- setValue(), if supported, writes through
- entry connected only during the iteration
- Map.entry() = unmodifiable, Java 9+
basics
~20 sMap.Entry represents one key-value pair in a Map. You get all pairs with map.entrySet() and loop over them, calling getKey() and getValue() on each entry. This avoids the extra lookup that keySet() plus get() makes for each key.
solid answer
~40 sMap.Entry is a nested interface representing a single key/value pair held by a Map. The idiomatic traversal is `for (Map.Entry<K,V> e : map.entrySet())`, then `e.getKey()` and `e.getValue()`. This is more efficient than iterating keySet() and calling map.get(key) for each key, which does a hash lookup per entry. During iteration, if the backing map supports it, an entry's `setValue(v)` writes through to the map. That connection is valid only during iteration of the entry-set view, and behaviour is undefined outside it or once the map has been modified other than through `setValue`, so copy a pair you want to keep with `Map.Entry.copyOf` (since Java 17). Since Java 9, `Map.entry(k, v)` creates an unmodifiable standalone entry (useful for Map.ofEntries). For stable iteration order use LinkedHashMap or TreeMap; HashMap order is unspecified.
go deeper
Can write the for-each over entrySet() and call getKey()/getValue() correctly.
Explains why entrySet() avoids the extra lookup per key of keySet()+get() and knows a supported setValue writes through.
Discusses entry validity during iteration, iteration-order guarantees per implementation, and unmodifiable Map.entry.
Reasons about view semantics, fail-fast iterators, and when to prefer streams or forEach over explicit entry iteration for clarity vs. performance.
### What a Map is A **Map** is a collection that stores data as **key-value pairs**: each unique *key* maps to one *value* (like a dictionary where the word is the key and the definition is the value). Java's `java.util.Map` is the interface; common implementations are `HashMap`, `LinkedHashMap`, and `TreeMap`. ### What Map.Entry is A Map needs a way to hand you *one* pair at a time. `Map.Entry<K,V>` is a **nested interface** (declared inside `Map`) that represents exactly one key-value pair. Its core methods are: - `getKey()` — returns the key of this pair. - `getValue()` — returns the value of this pair. - `setValue(V newValue)` — an optional operation that changes the value; where supported, it **writes through** to the underlying map (the map actually changes). ### Getting the entries: entrySet() `map.entrySet()` returns a `Set<Map.Entry<K,V>>` — a view (not a copy) of all the pairs. "View" means it is backed by the map: it reflects the map's current contents. You loop over it: ```java for (Map.Entry<String,Integer> e : map.entrySet()) { System.out.println(e.getKey() + "=" + e.getValue()); } ``` ### Why entrySet() beats keySet() An alternative is to loop over `map.keySet()` (just the keys) and call `map.get(key)` for each. That performs **two operations per pair**: one to produce the key and one hash lookup to fetch the value. `entrySet()` gives you both at once, so it skips that lookup for **every pair**, which adds up on large maps. ### setValue write-through and validity During iteration you may call `e.setValue(x)` to update that pair in place, if the backing map supports it (an unmodifiable map's entries throw `UnsupportedOperationException`). The `Map.Entry` documentation scopes the connection to the iteration: it is "valid *only* during iteration of the entry-set view". An entry's behaviour is undefined outside that iteration, and also if the map "has been modified after the Entry was returned by the iterator, except through the `setValue` method". So you should not stash entries in a list and read them later expecting them to stay live. To keep a pair, copy it with `Map.Entry.copyOf(e)`, since Java 17, which the documentation names as the way to guarantee an entry is disconnected. It rejects a null key or value. ### Unmodifiable standalone entries (Java 9+) `Map.entry(key, value)` creates a **self-contained, unmodifiable** entry not tied to any map. It rejects nulls and throws on `setValue`. It is mainly used with `Map.ofEntries(...)` to build small unmodifiable maps. ### Iteration order The order in which `entrySet()` yields pairs depends on the implementation: `HashMap` is **unordered/unspecified**, `LinkedHashMap` preserves insertion (or access) order, and `TreeMap` yields keys in sorted order. Don't rely on HashMap order.
- Why is iterating entrySet() generally faster than keySet() then map.get()?entrySet() yields the key and value together, so it avoids the extra hash lookup that map.get(key) performs for every key.
- What does Map.entry(k, v) give you that an iteration entry does not?An unmodifiable, standalone entry not backed by any map: it rejects null key/value and throws UnsupportedOperationException on setValue; useful with Map.ofEntries.
- Claiming keySet()+get() is just as fast as entrySet()
- Thinking setValue() only changes a copy, not the map
- Assuming HashMap iterates in insertion or sorted order
- Storing iteration entries and reading them after the loop
- Map.Entry
- Java 1.2
- Map.entry factory method
- Java 9
Assumes JDK 27; Map.entry arrived in Java 9 and Map.Entry.copyOf in Java 17, so both are on 25 LTS, and this contract reads the same at JDK 25.
context
- Map.Entry (Java SE 27 & JDK 27)docs.oracle.com
- Map (Java SE 27 & JDK 27)docs.oracle.com