如何删除java hashmap中特定对象的所有映射? [英] How to remove all the mappings of a particular object in java hashmap?
本文介绍了如何删除java hashmap中特定对象的所有映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在java hashmap中有一个多对一映射。我使用 java.util.HashMap.values()
遍历所有值。现在,如果我想删除一个特定的值和所有相应的键,那么我应该怎么做?
只需使用 java.util.HashMap .remove(Object key)
其中一个键足够了吗?
解决方案
在这个例子中,你可以
代码
//测试图
final Map< String,String> map = new HashMap< String,String>();
map.put(Key1,Value);
map.put(Key2,Value);
map.put(Key3,Value);
//移除地图。该集合对于删除所有值而非仅删除一个值是必需的。
map.values()。removeAll(Collections.singleton(Value));
//打印地图以确认其工作。
System.out.println(打印地图);
for(final String key:map.keySet()){
System.out.println(key +=+ map.get(key));
}
输出
打印地图
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
这篇关于如何删除java hashmap中特定对象的所有映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文