In Java, entrySet() returns a Set<Map.Entry<K, V>> view of a TreeMap. Each element is one key/value pair, and iteration visits them in ascending key order. It is the most efficient way to loop over keys and values together.
Unlike the snapshots from firstEntry() and friends, the entries you get while iterating are the real tree nodes: setValue changes the value in the map. The set itself is a live view that supports removal but not addition.
An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.
Syntax
The classic loop over keys and values:
Java
TreeMap<String, Integer> stock = new TreeMap<>();
for (Map.Entry<String, Integer> e : stock.entrySet()) {
String key = e.getKey();
Integer value = e.getValue();
}
Call
What it does
map.entrySet()
Live view of all entries, in key order.
e.setValue(v)
Replaces the value in the map (during iteration).
map.entrySet().removeIf(p)
Removes every entry that matches.
Looping over entrySet() avoids the extra O(log n) get call per key that a keySet() loop needs.
Library declarations
Java
// java.util.TreeMap<K, V>
public Set<Map.Entry<K, V>> entrySet()
// Declared in Map<K, V> and SortedMap<K, V>
Parameters
Parameter
Description
(none)
entrySet takes no parameters.
Return Value
Return Value
Description
Set<Map.Entry<K, V>>
A live view of the mappings, iterated in ascending key order.