1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java使用迭代器删除元素_使用Java从地图中删除元素

java使用迭代器删除元素_使用Java从地图中删除元素

时间:2020-09-13 23:40:54

相关推荐

java使用迭代器删除元素_使用Java从地图中删除元素

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 valuemap.values().removeIf(value -> !value.contains("1"));// remove by keymap.keySet().removeIf(key -> key != 1);// remove by entry / combination of key + valuemap.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条目。

翻译自: //03/removing-elements-map-java.html

java使用迭代器删除元素

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。