Clear HashMap values ​​while saving keys

Is there a way to clear all values ​​while keeping the keys?

Mine HashMap

is equal <String,String>

, so I should just loop through and replace each value

with null

? Is there a better way to do this?

+3


source to share


3 answers


You can use Map#replaceAll

if using Java 8+:

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

      

If not, then looping Entry

is probably the easiest way. From the link above, the standard implementation is Map#replaceAll

equivalent:



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

      

If the function is a parameter, you can do this:

for (Map.Entry<K, V> entry : map.entrySet()) {
    entry.setValue(null);
}

      

+7


source


I would keep this simple and collect the headers in a list or customize and then create a new HashMap on each line iterating over the list instead of trying to recycle the same map.



+3


source


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

      

+1


source







All Articles