clear all values of hashmap except two key/value pair

Viewed 5681

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 ?

2 Answers

yet shorter (since Java 2):

map.keySet().retainAll(myKeys);

Since keySet() still wraps the original HashMap, its #retainAll() affects the Map.

myKeys is a collection of keys, e.g.: myKeys = List.of("key1", "key2")

Related