How do I use the Map.forEach() default method?

The forEach() method in the Map interface in Java 8, allows you to iterate over each entry in the map, allowing you to use each key-value pair in some way.

Here’s a basic usage of the forEach() method:

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class MapForEachExample {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("Apple", 10);
        map.put("Orange", 20);
        map.put("Banana", 30);

        // Use the forEach method. Here, each key-value pair is printed.
        map.forEach((key, value) -> System.out.println("Key: " + key + ", Value: " + value));


Key: Apple, Value: 10
Key: Orange, Value: 20
Key: Banana, Value: 30

In this example, a HashMap is created and populated with some data. The forEach method is then called on this map, with a lambda expression that accepts a key and a value, then prints them. The key and value parameters represent the current key-value pair the forEach method is handling. In this lambda expression, they are printed to the console.

This operation is applied to each entry in the map, hence the name forEach.

Using the forEach method with lambda expressions has several benefits:

  1. Improved Readability: Traditional iteration requires creating an iterator, a while or for loop, and handling each element. With forEach and lambdas, you can express what you want to do with each element clearly and concisely, making the code easier to read and understand
  2. Concurrency Safety: The forEach method is inherently safer to use in concurrent environments. You don’t need to worry about ConcurrentModificationException errors which you might get while using an Iterator and modifying the collection concurrently.
  3. Less Boilerplate Code: The forEach function in combination with a lambda function provides a way to iterate over a collection with fewer lines of code compared to using iterators
  4. Functional Programming: Lambda expressions and functional interfaces pave the way towards functional programming in Java, which allows for more expressive ways to manipulate collections.

Remember, although forEach can make your code more concise, it does not necessarily make it faster.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.