Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear HashMap Values While Retaining Keys

Tags:

java

hashmap

Is there a way to clear all of the values, while retaining the keys?

My HashMap is <String,String>, so should I just loop through and replace each value with a null? Is there a better way to do it?

like image 407
Adam_G Avatar asked Dec 14 '22 19:12

Adam_G


2 Answers

You can use Map#replaceAll if you are using Java 8+ :

map.replaceAll((k, v) -> null);

If not, looping over the Entrys will probably be the simplest way. From the link above the default implementation of Map#replaceAll is equivalent to:

for (Map.Entry<K, V> entry : map.entrySet())
    entry.setValue(function.apply(entry.getKey(), entry.getValue()));

Where function is the parameter, so you could do this:

for (Map.Entry<K, V> entry : map.entrySet()) {
    entry.setValue(null);
}
like image 76
Alex - GlassEditor.com Avatar answered Jan 04 '23 13:01

Alex - GlassEditor.com


I would keep it simple and collect the headers in a list or set then create a new HashMap at each line by looping over the list instead of trying to recycle the same map.

like image 30
assylias Avatar answered Jan 04 '23 13:01

assylias