In Java, getOrDefault(key, defaultValue) returns the value stored under key in a TreeMap, or defaultValue if the key is not present. It never stores the default.
It removes the "get, then check for null" step, and is handy with numbers, where a missing price can count as 0. A key that is present but mapped to null returns null, not the default.
An instance method of java.util.TreeMap, added in Java 8 as part of the Map interface. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe. TreeMap inherits the Map default implementation, which uses one get plus a containsKey only when the value is null.
Syntax
Pass the key and the value to use when it is missing.
Java
TreeMap<String, Integer> priceInCents = new TreeMap<>();
int p = priceInCents.getOrDefault("caviar", 0); // 0 (missing key)
Call
What it does
map.getOrDefault(k, 0)
Missing numbers count as 0.
map.getOrDefault(k, "free")
A placeholder text for empty slots.
map.getOrDefault(k, d) == d
Not a reliable "missing" test; use containsKey.
Unlike computeIfAbsent() or putIfAbsent(), the default value is only returned, never stored, so the map size does not change.
Library declarations
Java
// java.util.TreeMap<K, V>
public V getOrDefault(Object key, V defaultValue)
// Default method of Map<K, V> since Java 8 (inherited by TreeMap)
Parameters
Parameter
Description
key (Object)
The key to look up. Not null under natural ordering.