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);
}
}
As per javadoc
ConcurrentModificationException may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible
transactionLogMap.remove(bigDecimal);
Instead of for loop use Iterator and call remove on iterator.
Example:
Iterator iter = transactionLogMap.keySet().iterator();
while(iter.hasNext())
{
iter.remove();
}
OR
You may consider using ConcurrentHashMap
Note: Typed in code, use as reference. There may be syntax errors.
The problem is in these lines
for (BigDecimal bigDecimal : transactionLogMap.keySet()) {
if(!inScopeActiveRegionIdSet.contains(bigDecimal)) {
transactionLogMap.remove(bigDecimal);
}
}
You are iterating through the transactionLogMap whilst also directly modifying the underlying Collection when you call transactionLogMap.remove, which is not allowed because the enhanced for loop cannot see those changes.
The correct solution is to use the Iterator:
Iterator<BigDecimal> it = transactionLogMap.keySet().iterator();//changed for syntax correctness
while (it.hasNext()) {
BigDecimal bigDecimal = it.next();
if(!inScopeActiveRegionIdSet.contains(bigDecimal)) {
it.remove();
}
}
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