Fundamentals 3 min read

Avoid Removing Elements While Iterating: Java ConcurrentModificationException Example and Fix

During a product bug investigation, the author demonstrates how removing entries from a Java HashMap while iterating triggers a ConcurrentModificationException, provides the faulty code, shows the exception stack trace, and presents a safe fix that collects keys first and removes them after iteration.

FunTester
FunTester
FunTester
Avoid Removing Elements While Iterating: Java ConcurrentModificationException Example and Fix

I encountered a bug in a company product where removing an element from a Map while iterating caused a crash due to a ConcurrentModificationException.

Important reminder: do not delete elements during iteration.

Reproduction code:

Map<Integer, Integer> abc = new HashMap<>();
abc.put(1, 2);
abc.put(2, 3);
abc.put(3, 4);
Set<Integer> keys = abc.keySet();
for (int i : keys) {
    if (i == 2) {
        abc.remove(i);
    }
}

The exception thrown is:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
    at java.util.HashMap$KeyIterator.next(HashMap.java:1453)
    at source.Practise.testDemo(Practise.java:23)
    at source.Practise.main(Practise.java:12)

Correct approach: first collect the keys to be removed, then delete them after the iteration completes.

Map<Integer, Integer> abc = new HashMap<>();
abc.put(1, 2);
abc.put(2, 3);
abc.put(3, 4);
Set<Integer> keys = abc.keySet();
List<Integer> toRemove = new ArrayList<>();
for (int i : keys) {
    if (i == 2) {
        toRemove.add(i);
    }
}
for (int i : toRemove) {
    abc.remove(i);
}

This method avoids modifying the collection during iteration, preventing the ConcurrentModificationException.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaHashMapiterationBugFixConcurrentModificationException
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.