且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从地图删除条目,而无需进行迭代

更新时间:2023-12-03 21:18:10

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

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.