EnumMap
is similar toMap
, exceptEnumMap
only takes theEnum
type as keys. Also, all the keys must be from a singleenum
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.
public void forEach(BiConsumer action)
The forEach()
method takes the BiConsumer
EnumMap
object.
The forEach()
method doesn’t return a value.
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);});}}
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 Lambda
forEach()
method. The Lambda function will execute for each entry of the map
object.