1. Introduction
A Map in Java is an object that stores associations between keys and values (key/value pairs). Given that a Map contains unique keys and each key maps to exactly one value, iterating over the elements (the key/value pairs) is a common task. This article will demonstrate several ways to iterate through a Map in Java, highlighting methods like the entrySet, keySet, and the Java 8 forEach method.
2. Program Steps
1. Import the necessary libraries.
2. Create and initialize a Map.
3. Use different methods to iterate over the map.
4. Output the keys and values of the map.
3. Code Program
// Step 1: Import the necessary libraries
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapIteration {
public static void main(String[] args) {
// Step 2: Create and initialize a Map
Map<String, Integer> fruitMap = new HashMap<>();
fruitMap.put("Apple", 10);
fruitMap.put("Banana", 20);
fruitMap.put("Cherry", 30);
fruitMap.put("Date", 40);
// Step 3: Use different methods to iterate over the map
// Using entrySet and for-each loop
System.out.println("Using entrySet and for-each loop:");
for (Map.Entry<String, Integer> entry : fruitMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// Using keySet and for-each loop
System.out.println("Using keySet and for-each loop:");
for (String key : fruitMap.keySet()) {
System.out.println("Key: " + key + ", Value: " + fruitMap.get(key));
}
// Using forEach with lambda expression
System.out.println("Using forEach with lambda:");
fruitMap.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
}
}
Output:
Using entrySet and for-each loop: Key: Apple, Value: 10 Key: Banana, Value: 20 Key: Cherry, Value: 30 Key: Date, Value: 40 Using keySet and for-each loop: Key: Apple, Value: 10 Key: Banana, Value: 20 Key: Cherry, Value: 30 Key: Date, Value: 40 Using forEach with lambda: Key: Apple, Value: 10 Key: Banana, Value: 20 Key: Cherry, Value: 30 Key: Date, Value: 40
4. Step By Step Explanation
Step 1: Start by importing the necessary libraries. In this program, we use Map, HashMap, and Set.
Step 2: Create and initialize a Map with some key/value pairs.
Step 3: Three different methods are employed to iterate over the map.
– First, we use entrySet along with a for-each loop. The entrySet method returns a Set view of the mappings contained in the map.
– Second, we utilize keySet in conjunction with a for-each loop. The keySet method returns a Set view of the keys contained in the map.
– Lastly, we implement the forEach method with a lambda expression. This method performs the given action for each entry in the map until all entries have been processed or the action throws an exception.
Step 4: In each iteration method, print out the keys and values of the map.