What is the EnumMap.forEach() method in Java?

EnumMap is similar to Map, except EnumMap only takes the Enum type as keys. Also, all the keys must be from a single enum type. For further details, refer here.

The forEach() method allows an action to be performed on each EnumMap object entry until all entries have been processed or an exception is thrown.

Syntax

public void forEach(BiConsumer action)

Parameters

The forEach() method takes the BiConsumerRepresents a function that accepts two input arguments and returns no result function interface as a parameter. This function is executed for each entry in the EnumMap object.

Return value

The forEach() method doesn’t return a value.

Code

The code below demonstrates how to use the forEach() method.

import java.util.EnumMap;
class ForEach {
enum Subject {
MATHS, SCIENCE, PROGRAMMING, ECONOMICS
};
public static void main( String args[] ) {
EnumMap<Subject, Integer> map = new EnumMap<>(Subject.class);
map.put(Subject.MATHS, 50);
map.put(Subject.SCIENCE, 60);
map.put(Subject.PROGRAMMING, 70);
map.forEach( (key, value) -> {
System.out.println(key +" - " +value);
});
}
}

Explanation

  • Line 3: We create an Enum for the subjects with the name Subject.

  • Line 7: We create an EnumMap with the name map.

  • Lines 8 to 10: We add three entries to the map.

  • Lines 11 and 12: We use the forEach() method to loop over the map. We pass a LambdaLambda 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 for the method that is expecting a functional interface as an argument. function as an argument to the forEach() method. The Lambda function will execute for each entry of the map object.

Free Resources