In Java 8 and later, you can use the forEach method of the Map interface to iterate over the key-value pairs of a Map and perform an action on each pair.
To use the forEach method to iterate over the key-value pairs of a Map, you can use the following syntax:
map.forEach((key, value) -> {
// code to be executed for each key-value pair
});
Here, map is the name of the Map, key is a variable that represents the current key being iterated over, and value is a variable that represents the current value being iterated over.
Here is an example of how you can use the forEach method to iterate over the key-value pairs of a Map and print them to the console:
import java.util.Map;
import java.util.HashMap;
public class MyClass {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("cherry", 3);
map.forEach((key, value) -> System.out.println(key + ": " + value));
// Outputs "apple: 1", "banana: 2", "cherry: 3"
}
}
It is important to note that the forEach method does not return a value, and it cannot be used to modify the elements of the Map. If you need to modify the elements of the Map, you can use a traditional for loop with an iterator, or you can use the replaceAll method of the Map interface.