Adam_G
Adam_G

Reputation: 7879

Clear HashMap Values While Retaining Keys

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?

Upvotes: 5

Views: 5298

Answers (3)

java_geek
java_geek

Reputation: 18035

for(String key : map.keySet()) {
  map.put(key, null);
}

Upvotes: 2

Alex - GlassEditor.com
Alex - GlassEditor.com

Reputation: 15497

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);
}

Upvotes: 8

assylias
assylias

Reputation: 328598

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.

Upvotes: 3

Related Questions