使用Java从地图中删除元素

关于从Java中的Map删除元素的非常简短的文章。 我们将专注于删除多个元素,而忽略了您可以使用Map.remove删除单个元素的Map.remove

以下Map将用于此帖子:

Map<Integer, String> map = new HashMap<>();
map.put(1, "value 1");
map.put(2, "value 2");
map.put(3, "value 3");
map.put(4, "value 4");
map.put(5, "value 5");

有几种删除元素的方法。 您可以手动遍历代码并将其删除:

for(Iterator<Integer> iterator = map.keySet().iterator(); iterator.hasNext(); ) {
  Integer key = iterator.next();
  if(key != 1) {
    iterator.remove();
  }
}

这是您无需访问Java 8+即可执行的操作。 从Map删除元素时,需要Iterator来防止ConcurrentModificationException

如果您确实有权使用Java(8+)的较新版本,则可以从以下选项中进行选择:

// remove by value
map.values().removeIf(value -> !value.contains("1"));
// remove by key
map.keySet().removeIf(key -> key != 1);
// remove by entry / combination of key + value
map.entrySet().removeIf(entry -> entry.getKey() != 1);

removeIfCollection可用的方法。 是的, Map本身不是Collection ,也无权访问removeIf本身。 但是,通过使用: valueskeySetentrySet ,将返回Map内容的视图。 此视图实现Collection允许在其上调用removeIf

valueskeySetentrySet返回的内容非常重要。 以下是JavaDoc的values摘录:

 * Returns a { this map. Collection} view of the values contained in * Returns a { @link Collection} view of the values contained in map.  * The collection is backed by the map, so changes to the map are  * reflected in the collection, and vice-versa.  *  * The collection supports element removal, which removes the corresponding  * mapping from the map, via the { @code Iterator.remove}, * mapping from the map, via the { Iterator.remove},  * { @code Collection.remove}, { @code removeAll},  * { @code retainAll} and { @code clear} operations. 

此JavaDoc解释说,由values返回的CollectionMap支持,并且更改CollectionMap将会改变另一个。 我认为我无法解释JavaDoc在说什么比在那儿已经写的更好的东西了。因此,我现在将不再尝试该部分。 我只显示了values的文档,但是当我说keySetentrySet也都由Map的内容作为后盾时,您可以信任我。 如果您不相信我,可以自己阅读文档。

这也使用旧版 Java版本链接回第一个示例。 该文档指定可以使用Iterator.remove 。 这是早先使用的。 此外, removeIf的实现与Iterator示例非常相似。 讨论完之后,我不妨展示一下:

default boolean removeIf(Predicate<? super E> filter) {
  Objects.requireNonNull(filter);
  boolean removed = false;
  final Iterator<E> each = iterator();
  while (each.hasNext()) {
    if (filter.test(each.next())) {
      each.remove();
      removed = true;
    }
  }
  return removed;
}

还有一点额外的东西。 但是,否则几乎是一样的。

就是这样。 除了告诉我要记住要使用以下内容之外,没有什么其他结论:使用valueskeySetentrySet将提供对removeIf访问,从而允许轻松删除Map条目。

翻译自: https://www.javacodegeeks.com/2019/03/removing-elements-map-java.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值