0
点赞
收藏
分享

微信扫一扫

Java删除Map中元素

胡桑_b06e 2022-03-26 阅读 94
java后端

前言:

关于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-lWrCHp9G-1648263083959)(https://juejin.cn/post/6844903859580567559)]

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

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

Integer key = iterator.next();

if(key != 1) {

iterator.remove();

}

}

复制代码

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-O7VdCvsD-1648263083960)(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-nVVgtBQd-1648263083960)(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-DUp9A1xO-1648263083961)(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-Cb1iiiUT-1648263083962)(https://juejin.cn/post/6844903859580567559)]

总结:

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

举报

相关推荐

0 条评论