Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the quickest way to remove an element from a Map by value in Java?

What's the quickest way to remove an element from a Map by value in Java?

Currently I'm using:

    DomainObj valueToRemove = new DomainObj();     String removalKey = null;      for (Map.Entry<String, DomainObj> entry : map.entrySet()) {         if (valueToRemove.equals(entry.getValue())) {             removalKey = entry.getKey();             break;         }     }      if (removalKey != null) {         map.remove(removalKey);     } 
like image 386
Supertux Avatar asked Aug 26 '09 16:08

Supertux


People also ask

How do I remove an item from a map in Java?

The Java HashMap remove() method removes the mapping from the hashmap associated with the specified key. The syntax of the remove() method is: hashmap. remove(Object key, Object value);

How do I remove a specific element from a HashMap?

HashMap remove() Method in Java 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.

How do I remove multiple elements from a HashMap in Java?

Assuming your set contains the strings you want to remove, you can use the keySet method and map. keySet(). removeAll(keySet); . keySet returns a Set view of the keys contained in this map.

Can we remove element from map while iterating?

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


1 Answers

The correct and fast one-liner would actually be:

while (map.values().remove(valueObject)); 

Kind of strange that most examples above assume the valueObject to be unique.

like image 71
Robbert Avatar answered Sep 28 '22 11:09

Robbert