8

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 2

11

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

0
5

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")

3
  • 1
    retainAll() only accepts a Collection. So code example should be map.keySet().retainAll(Set.of("key1", "key2")); // Java 9+ syntax
    – rmuller
    Feb 17, 2022 at 13:04
  • @rmuller , many thanks. I'm fixing the code example from the incorrect .retainsAll("key1", "key2") into .retainAll(Set.of("key1", "key2"))
    – epox
    Mar 10, 2022 at 22:47
  • Just nitpicking. IMHO Set.of() is neater in this example
    – rmuller
    Mar 11, 2022 at 11:02

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.