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
| Expected | O(1) |
|---|---|
| Worst case | O(n) |
| Extra space | O(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;
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.