In Java, there are several ways to iterate through a Map. Here are three commonly used ways to iterate through a Map:
Using entrySet() The entrySet() method of the Map interface returns a set of key-value pairs as Map.Entry objects. You can then iterate through the set using a for-each loop to access each key-value pair.
Here’s an example code that demonstrates how to iterate through a Map using entrySet():
import java.util.HashMap;
import java.util.Map;
public class Example {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " = " + value);
}
}
}
In this example, we create a Map that maps three strings to three integers. We then use a for-each loop to iterate through the Map using entrySet(). For each key-value pair, we extract the key and value using the getKey() and getValue() methods of the Map.Entry interface.
Using keySet()
The keySet() method of the Map interface returns a set of keys in the Map. You can then iterate through the set using a for-each loop to access each key. You can then use the get() method of the Map interface to retrieve the corresponding value.
Here’s an example code that demonstrates how to iterate through a Map using keySet():
import java.util.HashMap;
import java.util.Map;
public class Example {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
for (String key : map.keySet()) {
Integer value = map.get(key);
System.out.println(key + " = " + value);
}
}
}
In this example, we create a Map that maps three strings to three integers. We then use a for-each loop to iterate through the Map using keySet(). For each key, we retrieve the corresponding value using the get() method.
Using forEach() Starting from Java 8, you can use the forEach() method of the Map interface to iterate through a Map. The forEach() method takes a lambda expression that is applied to each key-value pair in the Map.
Here’s an example code that demonstrates how to iterate through a Map using forEach():
import java.util.HashMap;
import java.util.Map;
public class Example {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
map.forEach((key, value) -> System.out.println(key + " = " + value));
}
}
In this example, we create a Map that maps three strings to three integers. We then use the forEach() method to iterate through the Map. The lambda expression passed to forEach() takes two parameters: the key and the value of each