How to iterate over Map or HashMap in java


In this post, we will see how  can we iterate a map in java. There are four ways of iterating over a map, HashMap or TreeMap.

Java HashMap tutorial:

  1. Using keyset() and for each loop(Java 5)
  2. Using keyset() and java Iterator
  3. Using EntrySet() and for each loop(Java 5)
  4. Using EntrySet() and java Iterator
if you remove elements while iterating , then 1st and 3rd option  will throw java.util.ConcurrentModificationException.
If you understand internal working of HashMap, then it may be easier for you to iterate an HashMap
Lets take an example:


Run it and you will get following output:


Related posts

Add Comment