0

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 ConcurrentModificationExceptionat 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.

mynameisJEFF
  • 4,073
  • 9
  • 50
  • 96
  • 2
    it is correct but why not check it yourself ? With an unit test for example ? Besides, you should avoid raw types : type your iterator such as `Iterator>` to avoid casts. – davidxxx Apr 21 '18 at 19:58
  • Your question is extremely confusing. In the topic, you talk about some exception. The exception is irrelevant for the question. And as @davidxxx said, [you should not use raw types](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). Elegancy is not part of the scope of Stack Overflow. When you have a working version, [Code Review](https://codereview.stackexchange.com/) is the place to go for this question. – Turing85 Apr 21 '18 at 19:58

0 Answers0