Java Map forEach() Method Tutorial

In this section we will learn what the Map forEach() method is and how to use it in Java.

What is Java Map forEach() Method?

The Java Map forEach() method is used to run a set of instructions for each entry (a pair of key and value) of a Map object.

Basically, this method takes a reference to another method and that’s the place where we define the instructions to be executed for each entry of a map object.

Note: we can’t use this method to change the elements of a map object however.

Java forEach() Method Syntax:

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

forEach() Method Parameters:

The method has one parameter of type BiConsumer which is a functional interface.

This means at its core the forEach() method only needs a reference to a method that has this signature:

  • It should take two arguments:
  • The first argument is of the same type as the keys in the target map object.
  • The second argument is of the same type as the values in the target Map object.

Also the return value of this reference method is void.

Note: we can create this reference method using the lambda expression or refer to an instance or static method.

forEach() Method Return Value:

The return value of the forEach() method is void.

forEach() Method Exceptions:

The method might throw two types of exceptions:

NullPointerException: We get this exception if the argument of this method is null.

ConcurrentModificationException: We get this exception if the entry to the method is found to be removed during iteration

Example: using Map forEach() method

import java.util.Map; 
import java.util.HashMap;
class Main{
    public static void main(String[] args) {
        Map<String,String> map = new HashMap<>();
        map.put("Omid","Dehghan");
        map.put("Jack","Bauer");
        map.put("Barack","Obama");
        map.put("Elon","Musk");
        map.put("Lex","Fridman");

        map.forEach((k,v)->{
            System.out.println(k+" "+v);
        });
    }
}

Output:

Elon Musk

Barack Obama

Omid Dehghan

Jack Bauer

Lex Fridman
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies