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
LinkedHashMapclass 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 BiConsumerLinkedHashMap 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 LinkedHashMapLinkedHashMap<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
LinkedHashMapobject and use theforEach()method to loop over it. We pass a function as an argument to thelambdaLambda 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. forEach()method. The lambda function will get executed for each entry of theLinkedHashMapobject. -
Then, we create a
BiConsumerfunction and pass it to theforEach()method in line , which applies the function to each entry in theLinkedHashMapobject.