How to remove all the mappings of a particular obj

2019-09-10 06:26发布

问题:

I have a many-to-one mapping in java hashmap. I iterate through all the values by using java.util.HashMap.values(). Now if I want to delete a particular value and all the corresponding keys, then what should I do?

Will just using java.util.HashMap.remove(Object key) with one of the keys suffice?

回答1:

In this example you can remove the values from a map without iteration.

Code

// The test map
final Map<String, String> map = new HashMap<String, String>();
map.put("Key1", "Value");
map.put("Key2", "Value");
map.put("Key3", "Value");

// Remove the map. The collection is necessary to remove all values instead of just one.
map.values().removeAll(Collections.singleton("Value"));

// Print the map to confirm it worked.
System.out.println("Printing Map");
for(final String key : map.keySet()) {
   System.out.println(key + " = " + map.get(key));
}

Output

Printing Map


标签: java hashmap