Java – How to Iterate a HashMap

In Java, there are 3 ways to loop or iterate a HashMap

1. If possible, always uses the Java 8 forEach.


	Map<String, String> map = new HashMap<>();
    map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));

2. Normal for loop in entrySet()


	Map<String, String> map = new HashMap<>();
	
	for (Map.Entry<String, String> entry : map.entrySet()) {
		System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
	}

3. Iterator, classic.


	Map<String, String> map = new HashMap<>();
       
	Iterator iter = map.entrySet().iterator();
	while (iter.hasNext()) {
		Map.Entry entry = (Map.Entry) iter.next();
		System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
	}

HashMap example

A full example, just for reference.

HashMapExample.java

package com.mkyong.calculator;

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

public class HashMapExample {

    public static void main(String[] args) {

        Map<String, Integer> map = new HashMap<>();
        map.put("web", 1024);
        map.put("database", 2048);
        map.put("static", 5120);

        System.out.println("Java 8 forEach loop");
        map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value));

        System.out.println("for entrySet()");
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
        }

        System.out.println("Iterator");
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue());
        }

    }

}

Output


Java 8 forEach loop
[Key] : database [Value] : 2048
[Key] : static [Value] : 5120
[Key] : web [Value] : 1024
for entrySet()
[Key] : database [Value] : 2048
[Key] : static [Value] : 5120
[Key] : web [Value] : 1024
Iterator
[Key] : database [Value] : 2048
[Key] : static [Value] : 5120
[Key] : web [Value] : 1024

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar