Hash map iteration: For loop using Random Access OR Iterator?

I need to iterate over a Hashmap to retrieve the values ​​stored in it.

As a bonus, I also have a list of keys. Therefore, I have the ability to iterate over it using an iterator or random access in a for loop. Which of the two options will provide the best way to accomplish this?

+3
source share
4 answers

There is no real difference, but if you get a list of keys by calling map.keySet(), then it is easiest to iterate over entrySet():

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

This way you can avoid having to create a collection of keys and then look up the value for each.

+3
source
for (Object O : TheMap.values()) {
    // Do something
}
+2
source

, , - O (n) . , O (n), , O (n) -0 . Hash O (1), , , O (n), , , ( ) O (1) . . , , , .

+2

If you just need values, and you don’t need to know the relationship between the key and the values, then the iterator will be faster, since you will save time to calculate the key value.

0
source

All Articles