I have read this post here. However, I do not understand how to extract the value pair from the iterator such that I can put it into a conditional expression to decide whether the key-value pair should be removed.
My original code is as follow, which throws this ConcurrentModificationException
at runtime:
for(Map.Entry<String, Order> o: orderIDHashMap.entrySet()) {
if(o.getValue().getOrderQuantity() == 0) {
orderIDHashMap.remove(o.getKey());
}
}
I tried to switch it to:
Iterator orderIDHashMap_iterator = orderIDHashMap.entrySet().iterator();
while(orderIDHashMap_iterator.hasNext()) {
Map.Entry<String, Order> pair = (Entry<String, Order>) orderIDHashMap_iterator.next();
if(pair.getValue().getOrderQuantity() ==0 ) {
orderIDHashMap_iterator.remove();
}
}
}
Question: Is my code above correct in implementing iterator to remove object Order
when Order quantity == 0
condition is met? If it is wrong, can someone provide me an answer or a more efficient / elegant way to code this up .
Thanks.