How to remove all the mappings of a particular object in java hashmap?

ぃ、小莉子 提交于 2019-12-13 04:48:40

问题


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


来源:https://stackoverflow.com/questions/30213956/how-to-remove-all-the-mappings-of-a-particular-object-in-java-hashmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!