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.
public void forEach(BiConsumer action)
The forEach()
method takes the BiConsumer
LinkedHashMap
object.
This method doesn’t return any value.
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);}}
In the code above, we create a LinkedHashMap
object and use the forEach()
method to loop over it. We pass a lambda
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 , which applies the function to each entry in the LinkedHashMap
object.