I have a HashMap. I loop through the map like this:
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Long key : map.keySet() ) {
int value = map.get(key);
value--;
map.put(key, value);
}
Is the way I'm using to update the map safe? Safe in the sense that it doesn't damage the map because of the iteration.
You could consider writing your code more efficiently as:
Map<Long, Integer> map = new HashMap<Long, Integer>();
for (Entry<Long, Integer> entry : map.entrySet() ) {
entry.setValue(entry.getValue() - 1);
}
This is a micro-optimization, but sometimes it matters, and you don't lose anything. It's shorter and clears up any ambiguity about the safety to boot!
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