This question already has an answer here:
I have a method test(), in which I am trying to compare two LinkedHashMaps against each other and modify the contents of one of the maps by removing the key/value pair if it is found in both LHM's. I keep getting a ConcurrentModificationException when running this method. I understand WHY I am getting the exception (since I am trying to modify the list that is being looped over). I'm not sure how to go forth with this however. I have this code so far:
private void test() {
LinkedHashMap<String, BigDecimal>testBene = new LinkedHashMap<String, BigDecimal>();
LinkedHashMap<String, BigDecimal>testDly = new LinkedHashMap<String, BigDecimal>();
testBene.put("ABCDEFG", BigDecimal.ZERO);
testBene.put("BCDEFGH", BigDecimal.ONE);
testBene.put("CDEFGHI", BigDecimal.TEN);
testDly.put("BCDEFGH", BigDecimal.ONE);
testDly.put("Foo", BigDecimal.TEN);
testDly.put("Bar", BigDecimal.TEN);
for (Entry<String, BigDecimal> beneKeySet : testBene.entrySet()) {
if (testDly.containsKey(beneKeySet.getKey())) {
for (Entry<String, BigDecimal> dlyKeySet : testDly.entrySet()) {
if ((dlyKeySet.getKey().equals(beneKeySet.getKey())) &&
dlyKeySet.getValue().equals(beneKeySet.getValue())) {
testBene.remove(dlyKeySet.getKey());
}
}
}
}
}
You could use an iterator:
for (Iterator<Entry<String, BigDecimal>> it = testBene.entrySet().iterator(); it.hasNext();) {
Entry<String, BigDecimal> beneKeySet = it.next();
if (testDly.containsKey(beneKeySet.getKey())) {
for (Entry<String, BigDecimal> dlyKeySet : testDly.entrySet()) {
if ((dlyKeySet.getKey() == beneKeySet.getKey()) && dlyKeySet.getValue() == beneKeySet.getValue()) {
it.remove();
}
}
}
}
Instead of removing the elements, put the keys that you want to remove into a separate collection. At the end, traverse that other collection, removing the keys from your map.
Alternatively, use the Iterator
interface instead of the for-each loop. This will enable you to use Iterator.remove()
to remove elements while iterating.
You cannot remove from a list you're currently iterating with a for each. Use the list's iterator to do this.
You can use EntrySet's iterator, or save all duplicated keys in another list, and later remove those from the map. Also, do not compare objects using ==, use the equals() function.
来源:https://stackoverflow.com/questions/15811799/concurrentmodificationexception-woes