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