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 ?
Assuming your set contains the strings you want to remove, you can use the
keySet
method andmap.keySet().removeAll(keySet);
.Contrived example:
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: