How do i remove the key value pair in the code below comparing with elements in HashMap?
Map<BigDecimal, TransactionLogDTO> transactionLogMap = new HashMap<BigDecimal, TransactionLogDTO>();
for (BigDecimal regionID : regionIdList) {// Generation new logDTO
// objects for each in scope
// region
transactionLogMap.put(regionID, new TransactionLogDTO());
}
Set<BigDecimal> inScopeActiveRegionIdSet = new HashSet<BigDecimal>();
for (PersonDTO personDTO4 : activePersons) {
inScopeActiveRegionIdSet.add(personDTO4.getRegion());
}
for (BigDecimal bigDecimal : transactionLogMap.keySet()) {
if (!inScopeActiveRegionIdSet.contains(bigDecimal)) {
transactionLogMap.remove(bigDecimal);
}
}
The problem is in these lines
You are iterating through the
transactionLogMapwhilst also directly modifying the underlyingCollectionwhen you calltransactionLogMap.remove, which is not allowed because the enhanced for loop cannot see those changes.The correct solution is to use the
Iterator: