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 Value if there is no mapping for the passed key.

  • Mapped value: Mapped value to the key if there is a mapping present for the passed key.

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 Enum for the subjects with the name Subject.

  • In line 7, we create an EnumMap with the name map.

  • In lines 8-10, we add three entries to the map.

  • In line 13, we call the get method for the key Subject.ECONOMICS. This will return null because there is no value mapping for the key Subject.ECONOMICS.

  • In line 16, we call the getOrDefault(Subject.ECONOMICS, 10) method. This will return 10 because there is no value mapped for the key Subject.ECONOMICS.

  • In line 19, we call the getOrDefault(Subject.MATHS, 10) method. This will return 50 because the value 50 is mapped for the key Subject.MATHS.

Note: Use the getOrDefault method when you need a default value if the value is not present in the EnumMap.

Free Resources