In this tutorial we will learn how to loop HashMap using following methods:
- For loop
- While loop + Iterator
Example:
In the below example we are iterating the HashMap using both the methods (for loop and while loop). In while loop we have used the iterator.
package beginnersbook.com;
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
public class Details
{
    public static void main(String [] args)
    {
        HashMap<Integer, String> hmap = new HashMap<Integer, String>();
        //Adding elements to HashMap
        hmap.put(11, "AB");
        hmap.put(2, "CD");
        hmap.put(33, "EF");
        hmap.put(9, "GH");
        hmap.put(3, "IJ");
        //FOR LOOP
        System.out.println("For Loop:");
        for (Map.Entry me : hmap.entrySet()) {
          System.out.println("Key: "+me.getKey() + " & Value: " + me.getValue());
        }
        //WHILE LOOP & ITERATOR
        System.out.println("While Loop:");
        Iterator iterator = hmap.entrySet().iterator();
        while (iterator.hasNext()) {
             Map.Entry me2 = (Map.Entry) iterator.next();
          System.out.println("Key: "+me2.getKey() + " & Value: " + me2.getValue());
        } 
    }
}
Output:
For Loop: Key: 2 & Value: CD Key: 3 & Value: IJ Key: 33 & Value: EF Key: 9 & Value: GH Key: 11 & Value: AB While Loop: Key: 2 & Value: CD Key: 3 & Value: IJ Key: 33 & Value: EF Key: 9 & Value: GH Key: 11 & Value: AB
Mathan says
Hi Chaitanya, Thank you very much for your wonderful and Helpful Articles. As a beginner, your website helps me a lot. thanks so much.
for this article, could you please advice me which loop will be efficient and can be best one for any appliance? since i am a beginner I could not give a use case for this.
Aditya says
Thanks you for the article could you please also let us know how the loop can be done to add data into the hashmap.
Saurabh says
Appreciate your efforts Chaitanya…Thanks for helping in learning collections specially