从地图删除条目,而无需进行迭代 [英] Remove entry from map without iterating

查看:72
本文介绍了从地图删除条目,而无需进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不使用值或键进行迭代的情况下从 Java Map中删除条目.基本上在我的地图中,我先使用containsKey()然后使用map.remove()删除它.

How do I remove entry from Java Map without using iteration using value or key. Basically in my map, I am using containsKey() then map.remove() to remove it.

推荐答案

您可以使用要删除的元素的键从地图上删除条目.

You remove an entry from a map by using the key of the element that you wish to remove.

map.remove("aKey");

如果您不知道元素的键,则必须进行迭代来获取它,例如:

If you don't know the key of the element you must iterate to obtain it such as this:

public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
     Set<T> keys = new HashSet<T>();
     for (Entry<T, E> entry : map.entrySet()) {
         if (value.equals(entry.getValue())) {
             keys.add(entry.getKey());
         }
     }
     return keys;
} 

这将返回在地图上找到的所有键.

This will return all the keys that were found on the map.

这篇关于从地图删除条目,而无需进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆