Skip to content

How to efficiently iterate over Map in Java?

In this post, I am going to share my analysis over the iterating each entries of Map in Java. At sometime it is required to fetch all key-values pairs stored in Map. Let we start the different way to iterate which will help you to decide which one is efficient.

1. Map.entrySet() with for Loop

The method Map.entrySet()returns a collection(Set<Map.Entry<K,V>>).  We can iterate over the entrySet return and get key and values pair using getKey() and getValue() method of Map.Entry<K,V>

for(Entry<String, String> entrySet: map.entrySet()) {
		System.out.println(entrySet.getKey());
        System.out.println(entrySet.getValue());
}

2. keySet() and values() method with for Loop

Use keySet() method to iterate the key values from the Map. This will return the Set<k> view.
Use values() method to iterate the value pair from the Map. This will return the Collection<K> view.

for (String key : map.keySet())
{
    System.out.println("key: " + name);
    System.out.println("Value: " + map.get(key));
}

3. Iterator over Map.entrySet()

We all know that Iterator is an interface in collection framework. Using the hasNext() method Iterator will loop over the map. It has an advantage using the remove() method we can remove the current element from the map.

Iterator<Map.Entry<String, String>> itr = map.entrySet().iterator(); 
while(itr.hasNext()) 
{ 
	Map.Entry<String, String> entry = itr.next(); 
    System.out.println("Key = " + entry.getKey());  
    System.out.println("Value = " + entry.getValue()); 
} 

4. Iterator over Map.keySet() and Map.values()

This is same as the above way. But using the method keySet() and values()

Iterator<String> itr = map.keySet().iterator();
while (itr.hasNext()) {
	System.out.println("Key = " + itr.next());
	System.out.println("Value = " + map.get(itr.next()));
}

5. forEach from Java 8

We can iterate a map using the lambda(->) expression in Java 8.

map.forEach((k,v) -> System.out.println("Key ="+ k + ", Value = " + v));

Conclusion

In my analysis, using the keySet() and entrySet() is more efficient to iterate over the Map. I have used the Calendar.getInstance().getTimeInMillis() to know the timing.

See also  Switch Expressions in Java - A quick introduction

Please do let me know of your thoughts about above analysis.

S.noMethodsMap SizeTime Taken to iterate in ms
1Map.entrySet() with for Loop10000000222
2keySet() and values() method with for Loop10000000369
3Iterator over Map.entrySet()10000000236
4Iterator over Map.keySet() and Map.values()10000000225
5forEach from Java 810000000414

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.