1. Introduction
Iterating over a HashMap in Java can be performed in several ways, such as using the entrySet(), keySet(), and values() methods, each offering a different perspective on the map data. This post will focus on using the entrySet() method and an enhanced for loop to iterate over the map.
2. Program Steps
1. Create and initialize a HashMap.
2. Utilize the entrySet() method to obtain a set view of the map.
3. Iterate over the set view using an enhanced for loop, and access both the key and value of each entry.
4. Print the key and value of each entry during the iteration.
3. Code Program
import java.util.HashMap;
import java.util.Map;
public class HashMapIteration {
public static void main(String[] args) {
// Step 1: Create and initialize a HashMap
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Banana", 20);
map.put("Cherry", 30);
// Step 2: Utilize the entrySet() method to obtain a set view of the map
// Step 3: Iterate over the set view using an enhanced for loop
// Step 4: Print the key and value of each entry during the iteration
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
}
Output:
Key: Apple, Value: 10 Key: Banana, Value: 20 Key: Cherry, Value: 30
4. Step By Step Explanation
Step 1: A HashMap named map is created and initialized with three entries, each with a String key and an Integer value.
Step 2: The entrySet() method is employed to retrieve a set view of the HashMap, which includes the map entries (key-value pairs).
Step 3: An enhanced for loop is used to iterate over the set view of the map. For each entry in the map, the getKey() and getValue() methods are used to access the key and value, respectively.
Step 4: During the iteration, the key and value of each entry are printed to the console, demonstrating the contents of the HashMap.