Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all items of a given value from a hashmap

Tags:

So I have a java hashmap like below:

hMap.put("1", "One");
hMap.put("2", "Two");
hMap.put("3", "Two");

I would like to remove ALL items where the value is "Two"

If I do something like:

hmap.values().remove("Two");

Only the first one is deleted, I want to remove them all, how can this be done?

like image 408
Anthony Webb Avatar asked Apr 07 '10 16:04

Anthony Webb


People also ask

How do I remove something from a HashMap?

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

Which method is used to remove all keys values pair from the HashMap?

Explanation: AbstractMap, WeakHashMap, HashMap and TreeMap provide implementation of map interface. 3. Which of these method is used to remove all keys/values pair from the invoking map? Explanation: None.

Can we remove elements from HashMap while iterating?

While iterating, check for the key at that iteration to be equal to the key specified. The entry key of the Map can be obtained with the help of entry. getKey() method. If the key matches, remove the entry of that iteration from the HashMap using remove() method.


1 Answers

hmap.values().removeAll(Collections.singleton("Two"));

EDIT: the (significant) disadvantage with this concise approach is that you are basically forced to comment it, saying something like

// remove("Two") would only remove the first one

otherwise, some well-meaning engineer will try to simplify it for you someday and break it. This happens... sometimes the well-intentioned do-gooder is even Future You!

like image 108
Kevin Bourrillion Avatar answered Oct 14 '22 10:10

Kevin Bourrillion