Quick revision
The short answer
We reduce these bugs in layers: make the safe operations the normal style (removeIf, replaceAll and stream filtering instead of manual removal in loops), return unmodifiable collections from APIs so callers cannot change shared data, turn on static analysis checks that detect removal inside for-each loops, use concurrent collections where data is shared between threads, and teach the cases in onboarding and review checklists. Each layer catches what the previous one misses, and we measure the findings to know it is working.
What to remember
In this answer, we built layered defences against modifying collections while iterating: standard idioms such as removeIf, replaceAll and stream filtering; APIs that return unmodifiable collections; static analysis that flags removal inside for-each loops, rolled out from warning to error; concurrent collections for shared data; and onboarding plus review checklists, with measurements showing whether the bug is actually disappearing.
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.
We reduce these bugs in layers: make the safe operations the normal style (removeIf, replaceAll and stream filtering instead of manual removal in loops), return unmodifiable collections from APIs so callers cannot change shared data, turn on static analysis checks that detect removal inside for-each loops, use concurrent collections where data is shared between threads, and teach the cases in onboarding and review checklists. Each layer catches what the previous one misses, and we measure the findings to know it is working.
Why this question is asked
When the same bug keeps appearing across teams, the problem is no longer one developer's mistake; it is that the organisation makes the mistake easy and the fix hard to remember. Modifying a collection while iterating it is a perfect example: it compiles, it often passes tests, and it fails in production with ConcurrentModificationException or silently skipped elements. Interviewers ask this leadership question to see whether we think in systems, standards, tools and defaults, rather than in reminders. In this answer, we will recap why the bug happens, then build the layers one at a time, and finish with how we would roll them out and measure them.
1Why This Bug Keeps Coming Back
A for-each loop runs on an iterator. If code removes from the collection directly inside that loop, the collection's modification counter changes and the iterator's next step throws ConcurrentModificationException. If the removed element was second-last, the loop just ends and skips the last element, with no error at all. Index loops have their own version: after remove(i), the next element shifts into i and is skipped.
So the bug has every property that makes bugs survive: the code looks natural, small test data often hides it, and the failure, when it comes, is far from obvious. Telling people to be careful does not scale. We need defaults and tools that make the safe path the easy one.
2Layer 1: Standard Idioms That Cannot Go Wrong
The first layer is a coding standard built on the bulk operations Java has had since Java 8. removeIf(predicate) removes matching elements in one pass. replaceAll(operator) transforms every element in place. For building a new collection, a stream with filter and toList(). For maps, map.entrySet().removeIf(...) and map.replaceAll(...). When the loop must do more than remove, an explicit Iterator with it.remove().
The standard should be short and say why: these methods cannot skip elements or throw, they state intent in one line, and on ArrayList removeIf is O(n) while repeated removes are O(n squared). A standard with reasons is followed; a list of rules without them is argued with.
3Layer 2: APIs That Do Not Hand Out Mutable Shared Data
Many of these bugs happen in a caller that modifies a collection it received from someone else, often while the owner is iterating it. The second layer removes that possibility: public methods return unmodifiable collections, List.copyOf, Set.copyOf, Map.copyOf, or records holding them. A caller that tries to change one gets UnsupportedOperationException immediately at the line that is wrong, instead of a ConcurrentModificationException somewhere else later.
4Layer 3: Static Analysis in the Build
Standards and API defaults reduce the bug; tools catch what remains, at the moment the code is written. Error Prone, for example, includes a check that flags modifying a collection inside an enhanced for loop over that same collection, and IntelliJ IDEA and SonarQube have comparable inspections (check the exact rule names for the versions you use). We enable the check in the shared build configuration so every repository gets it without each team setting it up.
The rollout matters as much as the rule. We start it as a warning, run it across all repositories to count existing findings, fix the hot spots, and then make it an error for new and changed code. Failing every build on day one with hundreds of old findings makes teams disable the check.
- Enable as warning everywhereshared build plugin config
- Count existing findingsper repository
- Fix the hot spotscode that runs in production paths
- Are findings near zero?YesMake it an error for all codeNoError for new and changed code only
- Track the count per releasepublish it to teams
5 steps in order. Play them, or step through them one at a time.
5Layer 4: Concurrent Collections Where Data Is Shared
Some of the reported bugs will not be single-threaded at all: a scheduler thread removes expired entries while a request thread iterates. No idiom fixes that, because ArrayList and HashMap are not thread-safe, and their fail-fast check is best effort only. The standard must say plainly: data shared between threads uses a concurrent collection, ConcurrentHashMap, CopyOnWriteArrayList for read-mostly lists, a concurrent queue, or an immutable snapshot that is replaced as a whole. Reviewers ask one question of every field collection in a singleton bean: which threads touch this?
| Situation | Standard fix |
|---|---|
| Remove matching elements, one thread | removeIf |
| Transform elements in place | replaceAll |
| Build a filtered result | stream().filter(...).toList() |
| Complex loop that also removes | explicit Iterator with it.remove() |
| Caller changes data it received | return List.copyOf / Map.copyOf |
| Data shared between threads | ConcurrentHashMap, CopyOnWriteArrayList, snapshot |
6Layer 5: Teaching and Measuring
The last layer is people. We add a short page to onboarding material that shows the three failure modes, the exception, the silent skip and the index shift, with the fix for each, and a line in the review checklist: any loop that modifies the collection it iterates. Short, concrete examples are remembered far better than general rules.
Finally, we measure. We track static analysis findings per release, production incidents with ConcurrentModificationException in the logs, and review comments on the topic. If the numbers fall, the layers are working; if one team's numbers stay high, we pair with that team rather than send another reminder. A leader's job here is to make the right thing the default, then check that it actually became the default.
7Follow-up questions
Why not just ban for-each loops that call remove?
That is what the static analysis rule effectively does, but a ban without an alternative just moves the bug into index loops. Pairing the rule with standard idioms such as removeIf gives people the replacement at the moment they are told to stop.
How do we handle legacy code with hundreds of findings?
We do not try to fix it all at once. We fix findings in code that runs in production hot paths or has caused incidents, apply the error level only to new and changed code, and let the rest be fixed when teams touch those files. The tracked count shows progress.
Do unmodifiable return values break existing callers?
They can, if a caller was modifying a returned collection. That is exactly the hidden coupling we want to find, but we roll it out carefully: introduce the change with a release note, run tests across consumers, and fix callers to copy the result if they really need to modify it.
8Conclusion
In this answer, we built layered defences against modifying collections while iterating: standard idioms such as removeIf, replaceAll and stream filtering; APIs that return unmodifiable collections; static analysis that flags removal inside for-each loops, rolled out from warning to error; concurrent collections for shared data; and onboarding plus review checklists, with measurements showing whether the bug is actually disappearing.
Open with
When a bug keeps recurring across teams, I treat it as a systems problem, not a reminder problem. This one is easy to write, often passes tests, and fails either with ConcurrentModificationException or by silently skipping an element.
Then, if they want more
So I would work in layers. First, a short coding standard built on the bulk operations: removeIf to remove matches, replaceAll to transform in place, stream filter and toList to build a new list, entrySet().removeIf for maps, and an explicit iterator with it.remove when the loop does more.
I'd include the reasons, including that removeIf is linear on ArrayList while repeated removes are quadratic. Second, API defaults: public methods return List.copyOf or Map.copyOf, so a caller that tries to modify shared data fails immediately at the wrong line, instead of breaking someone else's iteration later.
Third, static analysis: Error Prone and IDE inspections can flag modifying a collection inside a for-each over it. I'd enable it in the shared build config as a warning, count findings, fix the hot paths, then make it an error for new code.
Fourth, for data shared between threads, the standard is concurrent collections or immutable snapshots, because no idiom makes ArrayList thread-safe. Fifth, onboarding examples and a review checklist line. And I would track findings and production exceptions per release, and work directly with any team whose numbers do not fall.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 8
- 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
- The Collections Framework, overview, java.util, package documentation
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 "Bugs from modifying collections while iterating keep appearing in reviews across teams....": https://scrivio-interview-library.netlify.app/java/lists/f3f811c169/