Key set iteration versus record set iteration

An employee today sent a review saying that the last piece of code is more efficient, because it does not need to search on the map at each iteration, like the previous one (# 1).

How does 2 (last) work? I just don’t understand how No. 1 and No. 2 are different.

**#1 snippet**:

for (String key : map.keySet())
{
   String value = map.get(key); // does lookup for every key
   // do something with value
}

**#2 snippet**:

for (Map.Entry<String, String> entry : map.entrySet())
{
   String key = entry.getKey();
   String value = entry.getValue();
}
+4
source share
2 answers

The problem is that it map.getusually has significant cost with a constant coefficient, while map.entrySet()iterating over is usually as cheap as iterating over map.keySet().

, TreeMap, O (n log n), O (n), HashMap, get .

+9

Snippet # 2 , .

# 1 map.get, O(n), - key. - , value.

, HashMaps , HashIterator:

 final class KeyIterator extends HashIterator
    implements Iterator<K> {
    public final K next() { return nextNode().key; }
}

final class EntryIterator extends HashIterator
    implements Iterator<Map.Entry<K,V>> {
    public final Map.Entry<K,V> next() { return nextNode(); }
}
+1

Source: https://habr.com/ru/post/1570043/


All Articles