Reputation: 2471
Suppose I have a Hashmap object myMap and it contains a set of keys and values,
key1, value1
key2, value2
...
...
let's say I have 30 keys in total.
Now I am getting a list of keys: key1, key2....,
say there are 28.
What is the best way to check myMap object and remove keys that are NOT in my list of keys? Do I have to iterate thru the hashmap keyset and compare each one in the list?
thanks.
Upvotes: 3
Views: 346
Reputation: 10055
Use the containsKey
method for each key you have, and if the method returns false
, remove it. Another option is to use Map#keySet#retainAll
.
Upvotes: 2
Reputation: 178303
Get the set of keys from the map. The set is backed by the map. Then call retainAll on it.
Set<String> keys = myMap.keySet();
keys.retainAll(keyList);
Here's the documentation on the keySet
method.
Here's the documentation on the retainAll
method.
Upvotes: 6