Java 25 (LTS) reference · Map and HashMap Methods
Java Map get() Method
Return the value for a key, or null if the key isn't present. Use getOrDefault() to avoid nulls.
Java 25 (LTS) Since Java 1.0
Syntax
map.get(key)
Parameters
| Parameter | Description |
|---|---|
keyObject |
The key to look up. |
Return value
The value, or null.
Examples
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>(Map.of("mug", 12));
System.out.println(stock.get("mug"));
System.out.println(stock.get("kettle"));
}
}
Output
12 null
Run this on your computer — see “Get Started” for setup.
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> stock = new HashMap<>();
try {
int qty = stock.get("kettle"); // unboxing null
} catch (NullPointerException e) {
System.out.println("get() returned null: use getOrDefault()");
}
}
}
Output
get() returned null: use getOrDefault()
Run this on your computer — see “Get Started” for setup.
Version history
| Version | Change |
|---|---|
| Java Java 1.0 | Added |
Related
map.getOrDefault()· Return the value for a key, or a default value if the key isn't present. Avoids null checks.map.containsKey()· Return true if the map has an entry for the key, even when its value is null. O(1) for HashMap.- Java HashMap · tutorial