How to iterate over Map or HashMap in java

Previous
Next

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:

1. IterateMapMain.java 

Run it and you will get following output:

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog