Reputation: 7879
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
Reputation: 15497
You can use Map#replaceAll
if you are using Java 8+ :
map.replaceAll((k, v) -> null);
If not, looping over the Entry
s 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
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