HashMap<K, V> · Java

getOrDefault / merge

Read with a fallback, or update in one lookup (e.g. counting).

public V getOrDefault(Object key, V defaultValue); public V merge(K key, V value, BiFunction<…> remapping)

Complexity

ExpectedO(1)
Worst caseO(n)
Extra spaceO(1)

A single lookup instead of get followed by put.

Tested example

Map<String, Integer> counts = new HashMap<>();
for (String word : new String[] {"a", "b", "a"}) {
    counts.merge(word, 1, Integer::sum); // insert 1 or add 1
}
assert counts.getOrDefault("a", 0) == 2;
assert counts.getOrDefault("z", 0) == 0;
Runs in the test suite on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/test/java/dev/bekadan/dsa/collections/HashMapExamples.java

Parameters

defaultValue / remapping
The fallback, or how to combine old and new values.

Behaviour

Returns
The value (or default); merge returns the new value.
Errors and preconditions
merge: NullPointerException for a null value or function.
Changes
getOrDefault: nothing. merge: adds, updates or (if the function returns null) removes.
Memory and invalidation
merge may resize.