How to Iterate Over a Map in Java


In this example we will show three different methods to loop a map in Java.

Source Code

1) Using for()

package com.beginner.examples;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class LoopMapExample1 {

	public static void main(String[] args) {

        Map map = new HashMap();
        map.put("1", "one");
        map.put("2", "two");
        map.put("3", "three");
        
        for (Map.Entry e : map.entrySet()) {
            System.out.println("Key : " + e.getKey() + " Value : " + e.getValue());
        }
    }
}

Output:

Key : 3 , Value : three
Key : 2 , Value : two
Key : 1 , Value : one

2) Using forEach()

package com.beginner.examples;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class LoopMapExample2 {

	public static void main(String[] args) {

        Map map = new HashMap();
        map.put("1", "one");
        map.put("2", "two");
        map.put("3", "three");

        map.forEach((key,value) -> System.out.println("Key : " + key + " , Value : " + value));
    }
}

Output:

Key : 3 , Value : three
Key : 2 , Value : two
Key : 1 , Value : one

3) Using java.util.Iterator

package com.beginner.examples;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class LoopMapExample3 {

	public static void main(String[] args) {

        Map map = new HashMap();
        map.put("1", "one");
        map.put("2", "two");
        map.put("3", "three");
       
        Iterator<Map.Entry> i = map.entrySet().iterator();
        while (i.hasNext()) 
        {
            Map.Entry entry = i.next();
            System.out.println("Key : " + entry.getKey() + " , Value :" + entry.getValue());
        }
    }
}

Output:

Key : 3 , Value : three
Key : 2 , Value : two
Key : 1 , Value : one

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments