Java 57: Map merge, computeIfAbsent & getOrDefault
easy⏱ 5 mincoursejava
merge: the counter idiom
map.merge(key, 1, Integer::sum) means: if key is absent, put 1; if present, replace with oldValue + 1. The remapping function is only called when the key already exists. This single line replaces map.put(k, map.getOrDefault(k, 0) + 1) and is the canonical frequency-counter idiom.
Map<String,Integer> freq = new HashMap<>();
for (String w : words) freq.merge(w, 1, Integer::sum);
// {the=3, cat=2, sat=1}
computeIfAbsent: the multimap idiom
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value) lazily creates the list only the first time a key is seen, then returns it so you can add to it. This is the standard way to build a Map<K, List<V>> multimap without a null check on every insert. The mapping function runs at most once per absent key.
getOrDefault, putIfAbsent, compute
getOrDefault(k, d) reads with a fallback without mutating. putIfAbsent(k, v) writes only if absent and returns the existing value if present. compute(k, (k,v) -> ...) always runs the remapping (with v possibly null) and can remove the entry by returning null. computeIfPresent runs only when the key exists. Each is a single atomic lookup — important under ConcurrentHashMap.
Frequency counter + multimap
Given the cat sat on the mat the cat, build a word-frequency Map using merge(word, 1, sum); print counts sorted by key. Then build a multimap grouping words by their length using computeIfAbsent(len, () => []).push(word); print each length and its words. Confirm the has count 3 and length-3 group contains the, cat, sat, mat (distinct, in first-seen order is fine).
merge can delete on null
If a merge or compute remapping function returns null, the entry is removed from the map. This is handy for decrement-to-zero counters: map.merge(k, -1, (a, b) -> { int v = a + b; return v == 0 ? null : v; }) removes the key when it hits zero — no separate cleanup pass.
Quiz: computeIfAbsent mapping calls
If you call computeIfAbsent(k, mk) three times for the same present key, how many times does the mapping function mk run? Once — only the first time, when the key was absent. The later two calls return the existing value without invoking mk. That's what makes it the right tool for lazy initialization.