Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear all values of hashmap except two key/value pair

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 ?

like image 602
Bipin Gawand Avatar asked Aug 04 '17 11:08

Bipin Gawand


People also ask

How remove all values from HashMap in Java?

To remove all values from HashMap, use the clear() method.

How delete all pairs of keys and values in HashMap?

HashMap clear() Method in Java The java. util. HashMap. clear() method in Java is used to clear and remove all of the elements or mappings from a specified HashMap.


2 Answers

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

like image 119
azro Avatar answered Oct 12 '22 23:10

azro


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

like image 43
epox Avatar answered Oct 12 '22 23:10

epox