Map.get()
Returns the value for a key, or `null`.
Available since: Java 1.2
Syntax
V get(Object key)Parameters
| Parameter | Type | Description |
|---|---|---|
| key | Object | The 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
nullA 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
0Notes
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
- Map.getOrDefault() — Returns the value for a key, or a fallback when the key is absent.
- Map.containsKey() — Checks whether a map has a key.
- Map.put() — Stores a value under a key, replacing the old one.
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.