forEach(BiConsumer): This method is available in java.util.EnumMap class of Java.
Syntax:
void java.util.Map.forEach(BiConsumer<? super K, ? super V> action)
This method performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
Parameters: One parameter is required for this method.
action: The action to be performed for each entry.
Throws:
1. NullPointerException - if the specified action is null.
2. ConcurrentModificationException - if an entry is found to be removed during iteration.
Approach 1: When no exception
Java
import java.util.EnumMap;public class EnumMapforEach {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {EnumMap<Colour, String> enumMap =new EnumMap<Colour, String>(Colour.class);enumMap.put(Colour.RED, "Red");enumMap.put(Colour.GREEN, "Green");enumMap.put(Colour.YELLOW, "Yellow");enumMap.put(Colour.ORANGE, "Orange");enumMap.forEach((key, value) ->System.out.println(key + "-" + value));}}
Output:
RED-Red
GREEN-Green
YELLOW-Yellow
ORANGE-Orange
Approach 2: NullPointerException
Java
import java.util.EnumMap;public class EnumMapforEach {public enum Colour {RED, GREEN, YELLOW, ORANGE};public static void main(String[] args) {EnumMap<Colour, String> enumMap =new EnumMap<Colour, String>(Colour.class);enumMap.put(Colour.RED, "Red");enumMap.put(Colour.GREEN, "Green");enumMap.put(Colour.YELLOW, "Yellow");enumMap.put(Colour.ORANGE, "Orange");enumMap.forEach(null);}}
Output:
Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.Map.forEach(Map.java:650)
No comments:
Post a Comment