Java Utility Library

Java LinkedHashMap - forEach() Method



The java.util.LinkedHashMap.forEach() method is used to perform the given action for each entry in this map until all entries have been processed or the action throws an exception.

Syntax

public void forEach(BiConsumer<? super K,? super V> action)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

action Specify the action to be performed for each entry.

Return Value

void type.

Exception

NA.

Example:

In the example below, the java.util.LinkedHashMap.forEach() method is used to perform the given action for each entry in the given LinkedHashMap.

import java.util.*;
import java.util.function.BiConsumer;

public class MyClass {
  public static void main(String[] args) {
    //creating a linkedhashmap
    LinkedHashMap<Integer, String> MyMap = new LinkedHashMap<Integer, String>();

    //populating the map
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");
    MyMap.put(105, "Sam");

    //creating an action
    BiConsumer<Integer, String> action 
            = new MyAction();   

    //using forEach method
    MyMap.forEach(action);  
  }
}
// Defining action in MyAction class 
class MyAction implements BiConsumer<Integer, String> { 
  public void accept(Integer k, String v) { 
    System.out.println("Key = " + k + 
                     ", Value = " + v); 
  } 
} 

The output of the above code will be:

Key = 101, Value = John
Key = 102, Value = Marry
Key = 103, Value = Kim
Key = 104, Value = Jo
Key = 105, Value = Sam

❮ Java.util - LinkedHashMap