Remove multiple keys from Map in efficient way?

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<> ();


System.out.println(map); //only contains "c"

Leave a Comment