Map.entrySet()
Returns all key and value pairs for iteration.
Available since: Java 1.2
Syntax
Set<Map.Entry<K, V>> entrySet()Return value
Set<Map.Entry<K, V>>A set of the map's pairs, linked to the map.
Examples
Iterating over pairs in a loop:
void main() {
Map<String, Double> rates = new TreeMap<>(Map.of("EUR", 1.0, "USD", 1.08));
for (var e : rates.entrySet()) {
IO.println(e.getKey() + " = " + e.getValue());
}
}Output:
EUR = 1.0
USD = 1.08Pairs in a stream: the key with the largest value:
void main() {
Map<String, Integer> votes = Map.of("Anna", 12, "Oleg", 17, "Ivan", 9);
String winner = votes.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse("nobody");
IO.println(winner);
}Output:
OlegNotes
It is the best way to iterate over a map when you need both keys and values: no extra get() on every step. The set is linked to the map — removing from it (for example with removeIf()) removes pairs from the map.
See also
- Map.Entry — A single key and value pair of a map.
- Map.keySet() — Returns the set of all keys of a map.
- Map.values() — Returns a collection of all values of a map.
- Map.forEach() — Runs an action for every pair of a map.
Related recipes
In the tutorial
- Maps: Map and HashMap — Maps in Java: key-value pairs, put and get, getOrDefault, counting with merge, TreeMap and LinkedHashMap.