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();
}
}
}
}