Clear HashMap values while saving keys
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 to share