Quick revision
The short answer
For counting I would use counts.merge(word, 1, Integer::sum), or Collectors.groupingBy(w -> w, Collectors.counting()) in a stream. For grouping, byCustomer.computeIfAbsent(o.customerId(), k -> new ArrayList<>()).add(o), or Collectors.groupingBy(Order::customerId). For a default, getOrDefault(key, fallback). The pitfalls are that getOrDefault does not insert the default and still returns null for a key explicitly mapped to null, putIfAbsent treats a null value as absent and returns the previous value, and we must never modify the same map inside a computeIfAbsent mapping function.
What to remember
In this answer, we replaced the check-then-act pattern with single Map methods. merge(word, 1, Integer::sum) counts, computeIfAbsent(id, k -> new ArrayList<>()).add(o) groups, and the stream forms are groupingBy with counting() or with a classifier. We saw that getOrDefault does not insert and returns null for keys mapped to null, that putIfAbsent treats null as absent and returns the previous value, and that a mapping function must never modify the map it runs in.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
For counting I would use counts.merge(word, 1, Integer::sum), or Collectors.groupingBy(w -> w, Collectors.counting()) in a stream. For grouping, byCustomer.computeIfAbsent(o.customerId(), k -> new ArrayList<>()).add(o), or Collectors.groupingBy(Order::customerId). For a default, getOrDefault(key, fallback). The pitfalls are that getOrDefault does not insert the default and still returns null for a key explicitly mapped to null, putIfAbsent treats a null value as absent and returns the previous value, and we must never modify the same map inside a computeIfAbsent mapping function.
Why this question is asked
Before Java 8, counting and grouping meant the same few lines over and over: get the value, check for null, create or update it, put it back. Those lines were easy to get slightly wrong and, with concurrent maps, impossible to make atomic. The default methods added to Map in Java 8 turn each pattern into one call. Interviewers ask this question to see whether we use them naturally and whether we know their edge cases, which are exactly where production bugs hide. In this answer, we will recap the old pattern, write the counting, grouping and default lookups with the modern methods and with streams, and then go through the pitfalls one by one with code.
1A Quick Recap of the Check-Then-Act Pattern
The classic way to count words was to read the current count, decide what to do, and write a new value back. That is three map operations and a branch for one logical update.
The code works for a single thread, but it hashes the key up to twice, it is verbose, and if counts were a ConcurrentHashMap shared by threads, two threads could both read 4 and both write 5, losing an update. Java 8's default methods on Map, such as merge, compute, computeIfAbsent, getOrDefault and putIfAbsent, express each pattern as one operation, and ConcurrentHashMap implements them atomically.
2Counting Words With merge
merge(key, value, function) inserts the value if the key is absent, and otherwise replaces the existing value with function(oldValue, value).
Notice the type difference: Collectors.counting() produces Long values, so the stream version gives a Map<String, Long>. Both are fine; the loop version is natural when we are already iterating for other reasons, and the stream version when the counts are the only result.
3Grouping Orders With computeIfAbsent
computeIfAbsent(key, mappingFunction) returns the existing value for the key, or, if there is none, calls the function, stores its result and returns it. Because it returns the value either way, we can chain add() onto it.
- Is 7 mapped to a non-null value?YesReturn that list, function not calledNoCall the function with 7
- Function returns a new ArrayList
- Is the result null?YesStore nothing, return nullNoStore the list under 7
- Return the stored listthe caller then calls
add(o)
4 steps in order. Play them, or step through them one at a time.
The function runs only when the key is missing, and a null result is never stored.
The lambda k -> new ArrayList<>() runs only the first time a customer appears, so we create exactly one list per customer. A common mistake is putIfAbsent(id, new ArrayList<>()), which creates a new list on every call and throws most of them away.
4Getting a Value With a Default, and the Pitfalls
getOrDefault(key, defaultValue) returns the mapped value, or the default if the key is absent. It reads only; it does not insert. And because it checks for the key, not for null, a key explicitly mapped to null returns null, not the default.
putIfAbsent has its own rule: it inserts when the key is absent or mapped to null, and returns the previous value, which is null when it inserted. So a null return does not tell us whether the key existed with null or did not exist. The cleanest way to avoid all of this is not to store null values in maps at all. ConcurrentHashMap forbids them outright.
5Never Modify the Map Inside the Mapping Function
The mapping function of computeIfAbsent, compute and merge runs while the map is in the middle of its own operation. If that function changes the same map, the map's internal state can become inconsistent.
The recursive call inserts other keys while the outer computeIfAbsent is still running, possibly triggering a resize under it. Since Java 9, HashMap detects this and throws ConcurrentModificationException; ConcurrentHashMap may throw IllegalStateException or, in some versions and cases, livelock. The fix is to compute outside the map: check with get, compute the value with ordinary code, then put it.
6Follow-up questions
What happens if the merge function returns null?
merge removes the entry. That is useful for counters that should disappear at zero, for example counts.merge(w, -1, (a, b) -> a + b == 0 ? null : a + b). The same rule applies to compute: returning null removes the mapping.
Can merge be used with a null value argument?
No. merge throws NullPointerException if the value argument is null, and also if the key is null for maps that do not support null keys. This is also why Collectors.toMap fails on null values, since it uses merge internally.
Which of these are atomic on ConcurrentHashMap?
computeIfAbsent, compute, computeIfPresent, merge and putIfAbsent are atomic on ConcurrentHashMap: the function runs at most once per call, under the bin's lock. That is why counting with merge on a ConcurrentHashMap is safe across threads, while get followed by put is not. The functions should be short, because other updates to the same bin wait for them.
7Conclusion
In this answer, we replaced the check-then-act pattern with single Map methods. merge(word, 1, Integer::sum) counts, computeIfAbsent(id, k -> new ArrayList<>()).add(o) groups, and the stream forms are groupingBy with counting() or with a classifier. We saw that getOrDefault does not insert and returns null for keys mapped to null, that putIfAbsent treats null as absent and returns the previous value, and that a mapping function must never modify the map it runs in.
Open with
For counting words I would loop and call counts.merge with the word, one, and Integer::sum. merge inserts one if the word is absent, and otherwise combines the old and new values with the function.
Then, if they want more
With streams it is groupingBy with identity and Collectors.counting, which gives Long values. For grouping orders by customer, I would use computeIfAbsent with the customer id and a lambda that creates a new ArrayList, then call add on the returned list.
The lambda only runs the first time a customer appears, unlike putIfAbsent with a new list, which allocates every time. The stream version is groupingBy of Order::customerId. For a default I would use getOrDefault.
The pitfalls: getOrDefault does not insert the default, and if a key is explicitly mapped to null it returns null, not the default. putIfAbsent inserts when the key is absent or mapped to null, and returns the previous value, so a null return is ambiguous. merge throws on a null value and removes the entry if the function returns null.
And I never modify the same map inside a computeIfAbsent function, for example in a recursive memoization; HashMap throws ConcurrentModificationException since Java 9, and ConcurrentHashMap can throw a recursive update error. On ConcurrentHashMap these methods are atomic, which is another reason to prefer them.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8, Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- java.util.HashMap, API documentation, The Collections Framework, overview
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Using Map methods added in Java 8 and later, write code that counts words in a...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/d0a51b83f9/