简体   繁体   中英

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?

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
}

Intuitively I would say use the iterator, since it may not require any lookups and just give you straight O(n) performance. note that your best case performance will be O(n) since you are touching every element of the set, and your average case performance will be O(n) times the big-O for your access method. Since Hash lookup has a high-probability of O(1) you will most likely be O(n) still, but with an iterator, since you are just calculating the next position, you are (I think) guaranteed O(1) access for the next element. This is why I would choose the iterator. Plus the constant time for next element calculation is probably better than the constant time for position lookup by hash.

如果您只需要这些值并且您不需要知道键和值之间的关系,那么迭代器将更快,因为您节省了计算键的has值的时间。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM