The Map.forEach method in Java provides a concise and elegant way to iterate over all key-value pairs in a Map. This method accepts a lambda function (or method reference), which processes each entry in the map.
Here’s how you can use Map.forEach for concise iteration:
Syntax:
map.forEach((key, value) -> {
// Your logic here
});
Example:
Suppose you have a map, and you want to print each key-value pair:
Map<String, Integer> map = new HashMap<>();
map.put("Apple", 10);
map.put("Orange", 20);
map.put("Banana", 30);
// Use forEach for iteration
map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));
Explanation:
- Lambda Expression:
(key, value)are the parameters representing the key and the value of each entry in the map.- The code block after
->defines what happens for each entry in the map.
- Conciseness:
- No need to use nested loops or explicitly retrieve entries from the map using
entrySetorkeySet.
- No need to use nested loops or explicitly retrieve entries from the map using
Use Cases:
- Logging or printing map entries.
- Applying transformations (e.g., modifying values).
- Collecting or filtering certain entries based on some condition.
Method Reference:
If your logic can be represented as a method, you can use a method reference:
map.forEach(System.out::println); // Prints entries like "Apple=10"
This keeps the code concise, readable, and functional.
