Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent Modification Exception in HashMap

Tags:

java

list

hashmap

I'm writing this program in Java and I'm getting a java.util.ConcurrentModificationException. The code excerpt is given below, please let me know if more code is required.

for (String eachChar : charsDict.keySet()) {
    if (charsDict.get(eachChar) < 2) {
        charsDict.remove(eachChar);
    }
}

charsDict is defined as

Map<String, Integer> charsDict = new HashMap<String, Integer>();

Please help me :)

like image 233
pratnala Avatar asked Jan 24 '26 22:01

pratnala


1 Answers

You're not allowed to remove elements from the map while using its iterator.

A typical solution to overcome this:

List<String> toBeDeleted = new ArrayList<String>();
for (String eachChar : charsDict.keySet()) {
    if (charsDict.get(eachChar) < 2) {
        toBeDeleted.add(eachChar);
    }
}

for (String eachChar : toBeDeleted) {
    charsDict.remove(eachChar);
}
like image 51
Vincent van der Weele Avatar answered Jan 27 '26 11:01

Vincent van der Weele



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!