Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Map.Entry

A single key and value pair of a map.

Available since: Java 1.2

Syntax

interface Map.Entry<K, V>
static <K, V> Map.Entry<K, V> Map.entry(K k, V v)

Examples

Pairs from entrySet():

void main() {
    Map<String, Integer> stock = new TreeMap<>(Map.of("pen", 12, "cup", 3));
    for (Map.Entry<String, Integer> e : stock.entrySet()) {
        IO.println(e.getKey() + " -> " + e.getValue());
    }
}

Output:

cup -> 3
pen -> 12

A pair can be created on its own:

void main() {
    var pair = Map.entry("Anna", 31);
    IO.println(pair.getKey() + " is " + pair.getValue());
    IO.println(pair);
}

Output:

Anna is 31
Anna=31

Notes

getKey() and getValue() read the pair, setValue() changes the value right in the map (if the map is modifiable). Pairs created with Map.entry() are immutable. For sorting pairs there are ready-made comparators Map.Entry.comparingByKey() and Map.Entry.comparingByValue().

See also

  • Map.entrySet() — Returns all key and value pairs for iteration.
  • Map.of() — Creates an unmodifiable map from key and value pairs.
  • 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.

Thanks for reading!

Donate to the site — we work hard for you.