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.
Please do let me know of your thoughts about above analysis.
S.no | Methods | Map Size | Time Taken to iterate in ms |
---|---|---|---|
1 | Map.entrySet() with for Loop | 10000000 | 222 |
2 | keySet() and values() method with for Loop | 10000000 | 369 |
3 | Iterator over Map.entrySet() | 10000000 | 236 |
4 | Iterator over Map.keySet() and Map.values() | 10000000 | 225 |
5 | forEach from Java 8 | 10000000 | 414 |