In Java, getOrDefault(key, defaultValue) returns the value a HashMap holds for key. If there is no mapping for that key, it returns defaultValue instead of null.
It only reads: the default is not stored in the map. That makes it a handy one-line replacement for "get, then check for null", especially for counters and configuration with fallback values.
An instance method of java.util.HashMap (class since Java 1.2): a hash table of key/value pairs with no guaranteed order, one null key, any number of null values, and no thread safety. getOrDefault was added in Java 8 as a default method of Map; HashMap overrides it with a single lookup.
Syntax
Pass the key and a fallback of the value type.
Java
Map<String, Integer> settings = new HashMap<>();
settings.put("volume", 70);
int v = settings.getOrDefault("volume", 50); // 70
int b = settings.getOrDefault("bright", 50); // 50 (not stored)
Call
What it does
map.getOrDefault(k, d)
Value for k, or d when k is missing.
map.getOrDefault(k, 0) + 1
The usual counting idiom, paired with put.
map.get(k)
Same lookup, but null for a missing key.
map.computeIfAbsent(k, f)
Stores the fallback instead of just returning it.
The default value is evaluated before the call, every time, even when the key exists. Pass a constant or a cheap expression.
Library declarations
Java
// java.util.HashMap<K, V> (Java 8+)
public V getOrDefault(Object key, V defaultValue)
// Default method in Map<K, V>, overridden by HashMap
Parameters
Parameter
Description
key (Object)
The key to look up.
defaultValue (V)
Returned when the map has no mapping for key. May be null.
Return Value
Return Value
Description
V
The stored value (even if it is null), or defaultValue when the key is missing.