Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a key from HashMap while iterating over it? [duplicate]

People also ask

How do I remove a specific key from a HashMap?

HashMap remove() Method in Java HashMap. remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Parameters: The method takes one parameter key whose mapping is to be removed from the Map.

What happens in HashMap If enter duplicates?

If you try to insert the duplicate key, it will replace the element of the corresponding key. HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values.

How do you remove a mapping while iterating over HashMap in Java?

You should always use Iterator's remove() method to remove any mapping from the map while iterating over it to avoid any error.

Can we modify HashMap while iterating?

It is not allowed to modify a map in Java while iterating over it to avoid non-deterministic behavior at a later stage. For example, the following code example throws a java. util. ConcurrentModificationException since the remove() method of the Map interface is called during iteration.


Try:

Iterator<Map.Entry<String,String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
    Map.Entry<String,String> entry = iter.next();
    if("Sample".equalsIgnoreCase(entry.getValue())){
        iter.remove();
    }
}

With Java 1.8 and onwards you can do the above in just one line:

testMap.entrySet().removeIf(entry -> "Sample".equalsIgnoreCase(entry.getValue()));

Use Iterator.remove().