Reputation: 995
I have a java map with string in its key and integer in its value. I want to remove a particular entry(key/value) from this map which doesn't have value greater than 5. Can any body suggest me how can I do this?
Thanks!
Upvotes: 1
Views: 1071
Reputation: 995
Ok! I did the job as following. Thanks to Stephen C:
Iterator<Map.Entry<String,Integer>> iter = TestMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,Integer> entry = iter.next();
if(entry.getValue() <= 5){
iter.remove();
}
}
Upvotes: 1
Reputation: 718788
If you've only got a regular map (i.e. no additional data structure that implements a reverse mapping), then your best option is to iterate the value set, test each value, and use Iterator.remove()
to remove the relevant ones.
If you have a secondary data structure, you may be able to use it to identify the entries to be removed. But the "cost" is that such a data structure takes space to represent and time to update ... and your code is more complex.
Upvotes: 4