Remove multiple keys from Map in efficient way?

2019-01-17 05:33发布

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. 

Then :

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 ?

标签: java map
2条回答
做自己的国王
2楼-- · 2019-01-17 05:51

Assuming your set contains the strings you want to remove, you can use the keySet method and map.keySet().removeAll(keySet);.

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.

Contrived example:

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"
查看更多
小情绪 Triste *
3楼-- · 2019-01-17 05:59

Just for the sake of completeness:

As guessed java.util.AbstractSet#removeAll really iterates over all entries, but with one little trick: It uses the iterator of the smaller collection:

if (size() <= collection.size()) {
    Iterator<?> it = iterator();
    while (it.hasNext()) {
        if (collection.contains(it.next())) {
            it.remove();
        }
    }
} else {
    Iterator<?> it = collection.iterator();
    while (it.hasNext()) {
        remove(it.next());
    }
}
查看更多
登录 后发表回答