Java删除Map中元素

前言:

关于Java从Map中删除元素的使用,可以使用删除单个元素的事实Map.remove。

示例:

初始化一个Map对象

Map 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”);

复制代码

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-f90sUKIr-1648991661829)(https://juejin.cn/post/6844903859580567559)]

有几种方法可以删除元素:

for(Iterator iterator = map.keySet().iterator(); iterator.hasNext(); ) {

Integer key = iterator.next();

if(key != 1) {

iterator.remove();

}

}

复制代码

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QVe6AnPo-1648991661830)(https://juejin.cn/post/6844903859580567559)]

如果不使用Java 8+,就可以使用Iterator以防止 ConcurrentModificationException异常。

如果您使用的

较新

版本的Java(8+),那么您可以这样:

// 通过value移除

map.values().removeIf(value -> !value.contains(“1”));

// 通过key移除

map.keySet().removeIf(key -> key != 1);

// 通过键/值的输入/组合删除

map.entrySet().removeIf(entry -> entry.getKey() != 1);

复制代码

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bsnv4XyE-1648991661831)(https://juejin.cn/post/6844903859580567559)]

removeIf是Collection s 的方法。一个Map本身不是一个Collection,也无法访问removeIf自己。但是通过使用:values,keySet或entrySet 此实现Collection允许removeIf在其上调用。

内容返回的values,keySet而且entrySet是非常重要的。以下是JavaDoc的说明摘要values:

* Returns a {@link Collection} view of the values contained in this 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},

* {@code Collection.remove}, {@code removeAll},

* {@code retainAll} and {@code clear} operations.

复制代码

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-0y5fDrIH-1648991661832)(https://juejin.cn/post/6844903859580567559)]

这个JavaDoc解释了Collection返回的values是由它支持的。文档指定Iterator.remove可以使用。此外实现removeIf与Iterator示例如下。

default boolean removeIf(Predicate super E> filter) {

Objects.requireNonNull(filter);

boolean removed = false;

final Iterator each = iterator();

while (each.hasNext()) {

if (filter.test(each.next())) {

each.remove();

removed = true;

}

}

return removed;

}

复制代码

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C491PlVO-1648991661832)(https://juejin.cn/post/6844903859580567559)]

总结:

使用 values,keySet或entrySet接入removeIf 更容易移除Map中的元素。

### JavaMap 删除元素的方法 在 Java 编程语言中,`Map` 是一种非常常用的数据结构,用于存储键值对。为了高效地管理这些数据,在某些情况下可能需要从 `Map` 中删除特定的元素。以下是几种常见的删除方式及其适用场景。 #### 使用 Iterator 的 remove 方法 可以通过 `Iterator` 遍历并安全地删除满足条件的元素。这种方式适用于任何版本的 Java,并能有效避免并发修改异常 (ConcurrentModificationException)[^2]。 ```java import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class RemoveExample { public static void main(String[] args) { Map<Integer, String> map = new HashMap<>(); map.put(1, "One"); map.put(2, "Two"); map.put(3, "Three"); Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<Integer, String> entry = iterator.next(); if ("Two".equals(entry.getValue())) { // 条件判断 iterator.remove(); // 安全删除 } } System.out.println(map); } } ``` #### 使用 Java 8 的 removeIf 方法 对于 Java 8 及更高版本,可以直接利用集合视图上的 `removeIf` 方法简化操作逻辑[^4]。此方法接受一个 Lambda 表达式作为参数,表示要移除元素所应满足的条件。 - **基于 Value 值删除** ```java map.values().removeIf(value -> !"One".equals(value)); ``` - **基于 Key 键删除** ```java map.keySet().removeIf(key -> key.equals(2)); ``` - **基于 Entry 组合条件删除** ```java map.entrySet().removeIf(entry -> entry.getKey() % 2 == 0 || !"Three".equals(entry.getValue())); ``` 以上三种调用分别展示了如何依据不同的标准筛选待删项[^5]。 #### 注意事项 尽管上述技术都可以成功完成任务,但在实际应用过程中仍需注意一些细节: - 如果尝试直接在一个增强型 for 循环 (`for-each`) 内部改变容器大小,则会抛出 ConcurrentModificationException 异常;因此推荐采用迭代器或者新特性如 `removeIf` 处理动态更新需求。 - 对于性能敏感的应用程序来说,应该考虑不同实现之间的效率差异——通常而言内置函数优化较好,而自定义循环则提供了更大的灵活性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值