【问题标题】:How to remove all the mappings of a particular object in java hashmap?java - 如何删除java hashmap中特定对象的所有映射?
【发布时间】:2015-05-13 11:49:47
【问题描述】:

我在 java hashmap 中有一个 多对一 映射。我使用java.util.HashMap.values() 遍历所有值。现在如果我想删除一个特定的值和所有对应的键,我该怎么办?

java.util.HashMap.remove(Object key) 与其中一个键一起使用就足够了吗?

【问题讨论】:

标签: java hashmap


【解决方案1】:

在此示例中,您无需迭代即可从地图中删除值。

代码

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

【讨论】:

  • 即将发布非常相似的内容。我有两个值,x 和 y。删除行是map.values().removeIf(y::equals);。结果相同。
  • 如果您使用的是 Java 8+,这很有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-21
  • 2018-08-13
  • 2021-11-05
  • 2019-04-07
  • 2014-06-14
  • 2020-06-29
相关资源
最近更新 更多