How to get a value from a map with a default
Short answer
getOrDefault() returns a fallback value if the key is missing:
void main() {
var prices = Map.of("tea", 3, "cake", 12);
IO.println(prices.getOrDefault("tea", 0));
IO.println(prices.getOrDefault("coffee", 0));
}Output:
3
0Add if missing
putIfAbsent() writes a value only if the key is not present yet:
void main() {
var settings = new HashMap<>(Map.of("theme", "dark"));
settings.putIfAbsent("theme", "light");
settings.putIfAbsent("lang", "en");
IO.println(new TreeMap<>(settings));
}Output:
{lang=en, theme=dark}Create on first access
computeIfAbsent() creates the value only when needed. Handy for grouping into lists:
void main() {
var byLetter = new TreeMap<Character, List<String>>();
for (String name : List.of("Anna", "Oleg", "Alex")) {
byLetter.computeIfAbsent(name.charAt(0), key -> new ArrayList<>()).add(name);
}
IO.println(byLetter);
}Output:
{A=[Anna, Alex], O=[Oleg]}Common mistake
Using get() without a check. It returns null for a missing key, and unboxing into an int throws:
void main() {
Map<String, Integer> stock = Map.of("tea", 5);
int coffee = stock.get("coffee");
}Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Map.get(Object)" is nullFunctions used in this recipe
- Map.getOrDefault() — Returns the value for a key, or a fallback when the key is absent.
- Map.computeIfAbsent() — Returns the value for a key, creating it with a function if the key is absent.
- Map.putIfAbsent() — Stores a value only if the key is not present yet.
- Map.get() — Returns the value for a key, or `null`.