[英]How to remove all the mappings of a particular object in java hashmap?
I have a many-to-one mapping in java hashmap. 我在Java hashmap中有一个多对一映射。 I iterate through all the values by using
java.util.HashMap.values()
. 我使用
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? 只需将
java.util.HashMap.remove(Object key)
与其中一个键一起使用就足够了吗?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.