Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Map.get()

Returns the value for a key, or `null`.

Available since: Java 1.2

Syntax

V get(Object key)

Parameters

ParameterTypeDescription
keyObjectThe key whose value is needed.

Return value

VThe value, or `null` if the key is absent.

Examples

A present and an absent key:

void main() {
    Map<String, String> capitals = Map.of("France", "Paris", "Japan", "Tokyo");
    IO.println(capitals.get("Japan"));
    IO.println(capitals.get("Peru"));
}

Output:

Tokyo
null

A trap: null into an int:

void main() {
    Map<String, Integer> scores = new HashMap<>();
    try {
        int s = scores.get("Anna");
    } catch (NullPointerException e) {
        IO.println("NullPointerException");
    }
    IO.println(scores.getOrDefault("Anna", 0));
}

Output:

NullPointerException
0

Notes

A null result means the key is absent (or that the value itself is null). Assigning such a result to an int or a double throws NullPointerException on unboxing. If you need a fallback use getOrDefault().

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.