Issue
I have a HashMap
with hundred of key/value pairs.
Now I have to delete all key/values except 2 key/value. I have use this way :
if(map!=null){
String search = map.get(Constants.search);
String context = map.get(Constants.context);
map = new HashMap<>();
map.put(Constants.search,search);
map.put(Constants.context,context);
}
But java 8 introduced removeIf()
for these kind of condition. How can I solve this problem with removeIf()
method ?
Solution
You'll need to it like this :
map.keySet().removeIf(k -> !(k.equals(Constants.search) || k.equals(Constants.context)));
It will iterate over the keys
and remove the ones for those the key
is not one of or two required keys
Answered By - azro
Answer Checked By - Mildred Charles (JavaFixing Admin)