What should we use to iterate over Map - keyset or entryset

There are various ways to iterate over Map in Java. In this article, we will learn what is the best way to iterating map in Java taking performance into consideration. Let us discuss various methods one by one.

Iterate Map using keyset 

This is one of the most common way used by many developers to iterate over Map in Java using keyset as shown below - 

for (Object key : map.keySet()) {
    Object value = map.get(key);
}

Iterate Map using entryset

Another way to iterate over map object in Java is using entryset as shown below -

for (Map.Entry entry : map.entrySet()) {
    Object key = entry.getKey();
    Object value = entry.getValue();
}

So what is different between iterating map using entryset and keyset - In the first case when we iterate using keyset for every key in the keySet the map.get() method is called, which - in the case of a HashMap - requires that the hashCode() and equals() methods of the key object be evaluated in order to find the associated value. 

Whereas, if we iterate using entryset the extra work of calculate hashCode() and equals() methods of the key object be evaluated in order to find the associated value is eliminated. If there is high collision the get() method will perform even poor. In case if you are using Treeset the get() method complexity is O(log2n). So, if you are iterating over map, it is recommended to use entryset in Java.

Author
Author: Amit Gupta
Published On: 15/04/2017
Last revised On: 15/04/2017
View all articles by Amit Gupta

Share this post

Comments

Comments
comments powered by Disqus

Navigation

Social Media