Java Utility Library

Java HashMap - forEach() Method



The java.util.HashMap.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.HashMap.forEach() method is used to perform the given action for each entry in the given HashMap.

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

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

    //populating MyMap
    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.print("Key = " + k); 
    System.out.println("   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 - HashMap