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 :)
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With