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?
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);
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With