What is the EnumMap.forEach() method in Java?
EnumMapis similar toMap, exceptEnumMaponly takes theEnumtype as keys. Also, all the keys must be from a singleenumtype. 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 BiConsumerEnumMap 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
Enumfor the subjects with the nameSubject. -
Line 7: We create an
EnumMapwith the namemap. -
Lines 8 to 10: We add three entries to the
map. -
Lines 11 and 12: We use the
forEach()method to loop over themap. We pass a function as an argument to theLambdaLambda 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. forEach()method. The Lambda function will execute for each entry of themapobject.