Traverse LinkedHashMap in Java: Methods & Examples
In Java, you can iterate through a LinkedHashMap using the entrySet() method. The specific steps are as follows:
- Obtain the entrySet of a LinkedHashMap.
- Iterate through the elements in the entrySet.
The example code is shown below:
LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("A", 1);
linkedHashMap.put("B", 2);
linkedHashMap.put("C", 3);
for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
The code above will output:
Key: A, Value: 1
Key: B, Value: 2
Key: C, Value: 3