1. Introduction
The LinkedHashMap is an extension of HashMap with an added feature of maintaining the insertion order, which means it contains the entries in the order they were inserted. In this tutorial, we’ll explore different ways to iterate over a LinkedHashMap.
2. Program Steps
1. Create and populate a LinkedHashMap.
2. Iterate and print using the traditional for-loop with entrySet().
3. Iterate and print using the forEach method.
4. Iterate and print only keys.
5. Iterate and print only values.
3. Code Program
import java.util.LinkedHashMap;
import java.util.Map;
public class IterateOverLinkedHashMap {
public static void main(String[] args) {
// Step 1: Create and populate a LinkedHashMap
LinkedHashMap<String, Integer> scores = new LinkedHashMap<>();
scores.put("Alice", 90);
scores.put("Bob", 85);
scores.put("Charlie", 78);
scores.put("Dave", 93);
// Step 2: Iterate and print using the traditional for-loop with entrySet()
System.out.println("Using entrySet with for-loop:");
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
System.out.println(entry.getKey() + " => " + entry.getValue());
}
// Step 3: Iterate and print using the forEach method
System.out.println("\nUsing forEach:");
scores.forEach((key, value) -> System.out.println(key + " => " + value));
// Step 4: Iterate and print only keys
System.out.println("\nKeys:");
for (String key : scores.keySet()) {
System.out.println(key);
}
// Step 5: Iterate and print only values
System.out.println("\nValues:");
for (Integer value : scores.values()) {
System.out.println(value);
}
}
}
Output:
Using entrySet with for-loop: Alice => 90 Bob => 85 Charlie => 78 Dave => 93 Using forEach: Alice => 90 Bob => 85 Charlie => 78 Dave => 93 Keys: Alice Bob Charlie Dave Values: 90 85 78 93
4. Step By Step Explanation
Step 1: We create a LinkedHashMap named scores and populate it with student names as keys and their scores as values.
Step 2: We use the traditional for-loop combined with the entrySet() method to iterate through each entry of the map. The entrySet() method returns a set view of the mappings contained in the map.
Step 3: We utilize the forEach method, a default method from the Map interface, which performs the given action for each entry in the map.
Step 4: To iterate and print only the keys, we use the keySet() method which returns a set view of the keys contained in the map.
Step 5: To iterate and print only the values, we use the values() method which provides a collection view of the values in the map.
Each of the iteration methods preserves the order in which the keys were inserted into the LinkedHashMap, demonstrating the predictable iteration order.