Quick revision
The short answer
I would publish a short internal guide with three rules, each shown with real before-and-after code from our own repositories: use single-operation methods such as computeIfAbsent, merge and getOrDefault instead of check-then-act sequences; return unmodifiable maps such as Map.copyOf from APIs and document who owns any mutable map; and replace Map<String, Object> data carriers with records. Then I would back the rules with static analysis in the shared build, such as Error Prone and Sonar rules, and a review checklist, so reviewers stop finding the same problems by hand.
What to remember
In this answer, we turned three repeated review findings into a system. Single-operation methods such as computeIfAbsent, merge and getOrDefault replace check-then-act sequences and are atomic on concurrent maps. APIs return unmodifiable maps such as Map.copyOf and document ownership of any mutable map. Records replace Map<String, Object> data carriers for type safety. Static analysis with Error Prone, Sonar and ArchUnit, a short checklist, and an internal guide built from our own code make the rules stick.
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.
I would publish a short internal guide with three rules, each shown with real before-and-after code from our own repositories: use single-operation methods such as computeIfAbsent, merge and getOrDefault instead of check-then-act sequences; return unmodifiable maps such as Map.copyOf from APIs and document who owns any mutable map; and replace Map<String, Object> data carriers with records. Then I would back the rules with static analysis in the shared build, such as Error Prone and Sonar rules, and a review checklist, so reviewers stop finding the same problems by hand.
Why this question is asked
When the same comment appears in code review across many teams, it is a sign that the problem is not individual carelessness but missing shared knowledge and missing automation. Reviewers spend time on it, authors feel nitpicked, and the issues that slip through become real bugs: lost updates in concurrent code, callers that corrupt a service's internal state, and runtime ClassCastExceptions from maps used as objects. Interviewers ask this leadership question to see whether a senior engineer can explain why each pattern is harmful, choose the right fix, and introduce it in a way that teams accept. In this answer, we will look at each misuse and its cost, the guidance that replaces it, the tooling that enforces it, and how to roll it out.
1Why Repeated Review Findings Call for a System
Each review comment fixes one instance and teaches one person. If ten teams each make the same mistake every month, reviewers are acting as a slow, inconsistent linter. The senior response is to remove the need for the comment: make the right way the obvious way through guidance, make the wrong way visible through tooling, and keep humans for the judgement calls that tools cannot make. To do that well, we first need to be precise about why each pattern is a problem, because guidance without reasons is ignored.
2Misuse 1: containsKey Followed by get
This is the check-then-act pattern: ask whether the key exists, then act on the answer with a second call.
In single-threaded code, the cost is a second hash lookup and extra lines. In concurrent code, it is a correctness bug. Between containsKey and get, another thread can remove the key, so get returns null. And two threads can both find the key missing and both run an expensive load. The single-operation methods do the check and the action as one step, and on ConcurrentHashMap they are atomic. The guide should note one trap: the function passed to computeIfAbsent must not modify the same map.
3Misuse 2: Mutable Maps Exposed From APIs
When a class returns its internal map directly, every caller can change the class's state without going through its methods. The class can no longer guarantee its own rules, and bugs appear far from their cause.
Map.copyOf returns an unmodifiable copy and rejects null keys and values. Collections.unmodifiableMap returns a read-only view that still reflects later changes, which is cheaper but means the caller sees updates. The guide should say which to use when, and require that any API that does pass a mutable map documents who owns it: whether the callee may keep it, and whether the caller may change it afterwards.
4Misuse 3: Maps Used as Ad Hoc Objects
A Map<String, Object> passed between methods, with keys like "name", "amount" and "currency", is an object without a type. Typos in keys compile, values need casts, and nobody can see from the signature what the map contains.
| Misuse | Cost | Replacement |
|---|---|---|
containsKey then get / put | extra lookups; races on shared maps | computeIfAbsent, merge, getOrDefault |
| Returning the internal mutable map | callers change internal state | Map.copyOf, documented ownership |
Map<String, Object> as data | typos compile, casts fail at runtime | a record |
Records make the replacement cheap: one line declares the type with its fields, equals, hashCode and toString. Maps remain the right tool for genuinely dynamic data, such as arbitrary JSON attributes or user-defined fields, and the guide should say so, so the rule is not applied blindly.
5Tooling That Enforces the Guidance
We put the checks where engineers already get feedback. Error Prone, which runs inside the compiler, has checks for several collection mistakes and can be extended; Sonar has rules for check-then-act on maps and for returning mutable internal collections; and ArchUnit tests can forbid Map<String, Object> in the public signatures of service and controller classes. We start these as warnings so teams are not blocked by old code, measure the count, and switch them to errors once the backlog is close to zero.
For what tools cannot judge, such as whether a map really is dynamic data, a short review checklist works better than long documents: three questions that link to the guide. Reviewers then point to the rule instead of rewriting the explanation every time.
6Rolling It Out So It Sticks
The guide must be short, one page per rule, and built from our own code: a real snippet from our repository, the bug or incident it caused if there was one, and the fixed version. Real examples persuade far better than general advice. I would present it in a brief session with the teams that had the most findings, invite their reviewers to improve the wording, and ship the tooling at the same time as the guide, so the rules are not just recommendations.
Then we measure: the number of review comments on these patterns and the number of static analysis findings should both fall over a few months. If a rule produces many false positives, we fix or drop it quickly, because one annoying rule can make teams ignore all of them.
7Follow-up questions
Is containsKey ever the right call?
Yes, when we only need to know whether the key exists and do not use the value, or when null values are allowed and we must tell a missing key from a null value. The problem is the combination of a check followed by a dependent action, not containsKey itself.
Should every returned map be copied?
Not necessarily. Copying costs time and memory for large maps on hot paths. Returning Collections.unmodifiableMap is a cheap read-only view, and returning an already immutable map, such as one built with Map.copyOf at construction, costs nothing extra. The rule is that callers must not be able to change our internal state, not that we must copy every time.
How do you get teams to accept new static analysis rules?
Introduce them as warnings, fix the shared libraries first so teams see the rules are achievable, keep false positives low, and explain each rule with an example from their own code. Teams resist rules that feel arbitrary and accept rules that clearly prevent bugs they have seen.
8Conclusion
In this answer, we turned three repeated review findings into a system. Single-operation methods such as computeIfAbsent, merge and getOrDefault replace check-then-act sequences and are atomic on concurrent maps. APIs return unmodifiable maps such as Map.copyOf and document ownership of any mutable map. Records replace Map<String, Object> data carriers for type safety. Static analysis with Error Prone, Sonar and ArchUnit, a short checklist, and an internal guide built from our own code make the rules stick.
Open with
When the same findings keep coming up across teams, I treat it as a missing shared standard, not individual mistakes, so I would fix it with guidance plus tooling.
Then, if they want more
The guidance is three short rules, each with a real before-and-after example from our codebase. First, prefer single-operation methods, computeIfAbsent, merge, getOrDefault, over containsKey followed by get or put. They avoid a second lookup, and on concurrent maps they are atomic, while check-then-act can return null or load the same value twice when another thread interferes.
Second, never return internal mutable maps. Return Map.copyOf or an unmodifiable view, and if an API does accept or return a mutable map, document who owns it. Third, replace Map of String to Object used as a data carrier with a record, so typos and wrong casts become compile errors; maps stay for genuinely dynamic data.
For tooling, I would add Error Prone and Sonar rules to the shared build and ArchUnit tests for public signatures, starting as warnings and switching to errors as the backlog clears, plus a three-question review checklist. Then I would measure whether review comments on these patterns drop, and remove any rule that produces too many false positives.
About this answer
- Last updated
- 12 November 2026
- 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 "Code reviews across teams keep finding the same map misuse: containsKey followed by get...": https://scrivio-interview-library.netlify.app/java/hashmap-internals/54e782e34a/