What is the EnumMap.getOrDefault method in Java?
EnumMap is similar to Map except that EnumMap only takes the Enum type as key. Also, all the keys must be from a single enum type. For further details refer here.
Syntax
public V getOrDefault(Object key,V defaultValue)
Parameters
key: Key whose value is to be returned.defaultValue: Default mapping of key.
Return value
-
Default value:
Default Valueif there is no mapping for the passedkey. -
Mapped value:
Mapped valueto thekeyif there is a mapping present for the passedkey.
Code
The code below demonstrates how to use the getOrDefault() method.
import java.util.EnumMap;class ComputeIfPresent {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);System.out.print("\nGetting value for key Subject.ECONOMICS using get(5) Method :" );System.out.println(map.get(Subject.ECONOMICS));System.out.print("\nGetting value for key Subject.ECONOMICS using getOrDefault Method :" );System.out.println(map.getOrDefault(Subject.ECONOMICS, 10));System.out.print("\nGetting value for key Subject.MATHS using getOrDefault Method :" );System.out.println(map.getOrDefault(Subject.MATHS, 10));}}
In the code above, we:
-
In lines 3-5, we create an
Enumfor the subjects with the nameSubject. -
In line 7, we create an
EnumMapwith the namemap. -
In lines 8-10, we add three entries to the
map. -
In line 13, we call the
getmethod for the keySubject.ECONOMICS. This will returnnullbecause there is no value mapping for the keySubject.ECONOMICS. -
In line 16, we call the
getOrDefault(Subject.ECONOMICS, 10)method. This will return10because there is no value mapped for the keySubject.ECONOMICS. -
In line 19, we call the
getOrDefault(Subject.MATHS, 10)method. This will return50because the value50is mapped for the keySubject.MATHS.
Note: Use the
getOrDefaultmethod when you need a default value if the value is not present in theEnumMap.