Write a Java Program to iterate HashMap using While and advance for loop.

HashMap can be traversed using multiple approaches in Java. The while-loop approach uses an Iterator to access each entry sequentially, while the enhanced for-loop iterates directly over the entrySet() of the HashMap.

The enhanced for-loop is generally preferred for readability, whereas the Iterator-based approach provides additional capabilities such as safe removal of elements during iteration.

Java Solution:

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

public class HashMapIterationExample {

    public static void main(String[] args) {

        Map<Integer, String> employeeMap = new HashMap<>();

        employeeMap.put(101, "John");
        employeeMap.put(102, "David");
        employeeMap.put(103, "Smith");
        employeeMap.put(104, "Alex");

        // Using while-loop with Iterator
        System.out.println("Using While Loop:");

        Iterator<Map.Entry<Integer, String>> iterator =
                employeeMap.entrySet().iterator();

        while (iterator.hasNext()) {
            Map.Entry<Integer, String> entry = iterator.next();

            System.out.println(

entry.getKey() + " : " + entry.getValue()

            );
        }

        // Using enhanced for-loop
        System.out.println("\nUsing Enhanced For Loop:");

        for (Map.Entry<Integer, String> entry : employeeMap.entrySet()) {
            System.out.println(

entry.getKey() + " : " + entry.getValue()

            );
        }
    }
}

Output: Using While Loop: 101 : John 102 : David 103 : Smith 104 : Alex

Using Enhanced For Loop: 101 : John 102 : David 103 : Smith 104 : Alex

Time Complexity: O(n), where n is the number of entries in the HashMap since each entry is visited exactly once.

Space Complexity: O(1), as no additional memory proportional to the number of entries is used during iteration.

Key Interview Points: • entrySet() iteration is more efficient than iterating over keySet() and calling get() for each key. • Iterator is useful when elements need to be removed during iteration. • HashMap does not guarantee insertion order of elements. • Common alternatives include forEach() introduced in Java 8 and Stream API iteration.