从地图中删除多个按键有效吗? [英] Remove multiple keys from Map in efficient way?
问题描述
我有一个 Map< String,String>
与大量的键值对。现在我想从 Map
中删除所选的键。以下代码显示了我做了什么。
I have a Map<String,String>
with large number of key values pairs. Now I want to remove selected keys from that Map
. Following code shows what I did to achieve that.
Set keySet = new HashSet(); //I added keys to keySet which I want to remove.
然后:
Iterator entriesIterator = keySet.iterator();
while (entriesIterator.hasNext()) {
map.remove( entriesIterator.next().toString());
}
这是正常工作。我只是想知道,什么是更好的方式来达到我的要求?
This is working. I just want to know, what would be a better way to achieve my requirement ?
推荐答案
假设您的集合包含要删除的字符串,可以使用 keySet
方法和 map.keySet()。removeAll(keySet);
。
Assuming your set contains the strings you want to remove, you can use the keySet
method and map.keySet().removeAll(keySet);
.
keySet
返回此地图中包含的键的Set视图。该集合由地图支持,因此对地图的更改将反映在该集合中,反之亦然。
keySet
returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa.
适用的示例:
Map<String, String> map = new HashMap<>();
map.put("a", "");
map.put("b", "");
map.put("c", "");
Set<String> set = new HashSet<> ();
set.add("a");
set.add("b");
map.keySet().removeAll(set);
System.out.println(map); //only contains "c"
这篇关于从地图中删除多个按键有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!