Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a hashmap: 'For' loop using Random Access OR Iterator?

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?

like image 987
Rajat Gupta Avatar asked Apr 20 '26 10:04

Rajat Gupta


2 Answers

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.

like image 184
matt b Avatar answered Apr 23 '26 03:04

matt b


for (Object O : TheMap.values()) {
    // Do something
}
like image 40
Erik Avatar answered Apr 23 '26 04:04

Erik