Write a Java program to iterate a HashMap using a while loop and an enhanced for loop.

A HashMap is usually traversed through its entrySet(). With a while loop you drive an Iterator over the entries yourself; with the enhanced for loop Java does that for you.

Key Points

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class IterateHashMap {

    public static void main(String[] args) {
        Map<Integer, String> employees = new LinkedHashMap<>();   // keeps insertion order for the demo
        employees.put(101, "Asha");
        employees.put(102, "Ravi");
        employees.put(103, "Neha");

        System.out.println("-- while loop with Iterator --");
        Iterator<Map.Entry<Integer, String>> it = employees.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, String> e = it.next();
            System.out.println(e.getKey() + " -> " + e.getValue());
        }

        System.out.println("-- enhanced for loop --");
        for (Map.Entry<Integer, String> e : employees.entrySet()) {
            System.out.println(e.getKey() + " -> " + e.getValue());
        }

        // Safe removal while iterating
        employees.entrySet().removeIf(e -> e.getKey() == 102);
        System.out.println("after removing 102: " + employees);
    }
}

Output

-- while loop with Iterator --

101 -> Asha

102 -> Ravi

103 -> Neha

-- enhanced for loop --

101 -> Asha

102 -> Ravi

103 -> Neha

after removing 102: {101=Asha, 103=Neha}

Good to Know

Java 8 added map.forEach((key, value) -> ...), which is the most concise way to read every entry.

If asked which loop to use, say the enhanced for loop for reading and the Iterator (or removeIf) when you need to remove entries during the loop.

Interview Tip

A concise interview answer is

I iterate over map.entrySet() so I get key and value together: with a while loop I use the entry Iterator's hasNext() and next(), and with the enhanced for loop I loop over the entries directly. I use the Iterator or removeIf() when I need to remove entries, because removing inside a for-each loop throws ConcurrentModificationException.

Last updated: 11 November 2026

Previous question: Write a Java program to count the frequency of each word in a string using a HashMap.

Next question: Write an efficient Java program to check whether a number is prime.

More Java Coding Questions interview questions

All Java Coding Questions questions