What is the LinkedHashMap.forEach() method in Java?

The LinkedHashMap class in Java is the same as the HashMap class, except LinkedHashMap maintains the insertion order, whereas the HashMap does not.

The LinkedHashMap class uses a doubly-linked list to maintain the insertion order.

You can read more about the LinkedHashMap class here.

The forEach() method allows for an action to be performed on each entry of the LinkedHashMap object until all entries have been processed or an exception is thrown.

Syntax

public void forEach(BiConsumer action)

The forEach() method takes the BiConsumerRepresents a function that accepts two input arguments and returns no result function interface as a parameter. This function is executed for each entry in the LinkedHashMap object.

This method doesn’t return any value.

Code

The code below demonstrates how to use the forEach() method.

import java.util.LinkedHashMap;
import java.util.function.BiConsumer;
class ForEach {
public static void main(String[] args) {
// create a LinkedHashMap
LinkedHashMap<Integer, String> numbers = new LinkedHashMap<>();
numbers.put(1, "One");
numbers.put(2, "Two");
numbers.put(3, "Three");
numbers.forEach( (key, value) -> {
System.out.println(key +" - " +value);
});
System.out.println("---------");
System.out.println("Using Bi Consumer function");
BiConsumer<Integer, String> biConsumer = (key, value) -> System.out.println(key + " # " + value);
numbers.forEach(biConsumer);
}
}

Explanation

  • In the code above, we create a LinkedHashMap object and use the forEach() method to loop over it. We pass a lambdaLambda expressions are anonymous functions (functions without a name). We can pass the Lambda expression as a parameter to another function. We can pass the lambda expression as an argument for the method which is expecting a functional interface as an argument. function as an argument to the forEach() method. The lambda function will get executed for each entry of the LinkedHashMap object.

  • Then, we create a BiConsumer function and pass it to the forEach() method in line 2222, which applies the function to each entry in the LinkedHashMap object.