What is the best way to Iterate over HashMap in Java? and not just HashMap, but any
Map implementation including old Hashtable, TreeMap, LinkedHashMap and relatively
newer ConcurrentHashMap, is a frequently asked queries from Java
Programmers, with some experience under his belt. Well, when it comes to
choosing between different
ways to iterate over Map in Java, it's you need, which plays an important
role. For example, if you just want to iterate over each entry of HashMap, without
modifying Map, then iterating over entry set using Java 1.5
foreach loop seems most elegant solution to me. Reason, it just two lines of
code using foreach loop and Generics,
and by getting set of entries, we get key and value together, without further
searching in HashMap. This makes it also fastest way
to loop over HashMap in Java. On the other hand, if you want to remove entries, while
iterating over HashMap, may be only selective entries, than foreach loop
will not help. Though foreach loop internally uses Iterator
for traversing elements, It doesn't expose handle to that Iterator, which means
you only have remove() method of Map to remove entries. That's not the ideal
way, especially if you had to remove lot of entries and that to during
Iteration. Your Iterator may also throw ConcurrentModificationException, depending
upon it's fail-safe
or fail-fast Iterator. E.g. Iterator of ConcurrentHashMap are weekly
consistent with actual Map and doesn't throw ConcurrentModificationException. This
leaves us with traditional while loop and Iterator combo, for looping HashMap
using Map.entrySet() and removing entries.