I need to iterate over a Hashmap to retrieve values stored in it.
As a bonus, I also have a list of the keys. So I have the option to iterate over it using the iterator or by random Access in a for loop. Which of the two options would provide a better performant way to do so?
There is no real difference, but if you are getting the list of keys by calling map.keySet(), then it's easiest to just iterate over the entrySet():
for (Map.Entry<K, V> entry : map.entrySet()) {
...
}
This way you can avoid having to both build a collection of keys and then looking up the value for each.
for (Object O : TheMap.values()) {
// Do something
}
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