How to delete a key value pair from a HashMap during Iteration in Java - Example tutorial
Suppose you have a Map or Dictionaries like HashMap or Hashtable, which contains key-value pairs like books and their prices, and you want to delete all books whose prices are greater than 40 USD, how do you that in Java? This is one of the most common scenarios while developing Java application and many Java programmer, will say that they will iterate over Map and check each entry and then use the remove(Object key) or remove(Object key, Object value) methods from java.util.Map to delete any mapping where the value is greater than 40 USD. Though the approach is right, the answer is wrong . Yes, we'll iterate over Map to check each value but we'll not use the two remove() methods from java.util.Map interface because they will throw ConcurrentModficationException when you call them to remove mapping during iteration. Instead, we'll use the Iterator.remove() method to delete any key-value pair, where the value is greater than 40 USD. The Iterator is a common interface which ...