【发布时间】:2015-05-13 11:49:47
【问题描述】:
我在 java hashmap 中有一个 多对一 映射。我使用java.util.HashMap.values() 遍历所有值。现在如果我想删除一个特定的值和所有对应的键,我该怎么办?
将java.util.HashMap.remove(Object key) 与其中一个键一起使用就足够了吗?
【问题讨论】:
-
是的,删除所有绑定在键上的值就足够了
我在 java hashmap 中有一个 多对一 映射。我使用java.util.HashMap.values() 遍历所有值。现在如果我想删除一个特定的值和所有对应的键,我该怎么办?
将java.util.HashMap.remove(Object key) 与其中一个键一起使用就足够了吗?
【问题讨论】:
在此示例中,您无需迭代即可从地图中删除值。
代码
// 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));
}
输出
Printing Map
【讨论】:
map.values().removeIf(y::equals);。结果相同。