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?
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With