关于从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);
removeIf
是Collection
可用的方法。 是的, Map
本身不是Collection
,也无权访问removeIf
本身。 但是,通过使用: values
, keySet
或entrySet
,将返回Map
内容的视图。 此视图实现Collection
允许在其上调用removeIf
。
由values
, keySet
和entrySet
返回的内容非常重要。 以下是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
返回的Collection
由Map
支持,并且更改Collection
或Map
将会改变另一个。 我认为我无法解释JavaDoc在说什么比在那儿已经写的更好的东西了。因此,我现在将不再尝试该部分。 我只显示了values
的文档,但是当我说keySet
和entrySet
也都由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;
}
还有一点额外的东西。 但是,否则几乎是一样的。
就是这样。 除了告诉我要记住要使用以下内容之外,没有什么其他结论:使用values
, keySet
或entrySet
将提供对removeIf
访问,从而允许轻松删除Map
条目。
翻译自: https://www.javacodegeeks.com/2019/03/removing-elements-map-java.html