Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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.08

Pairs 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:

Oleg

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.