What is the EnumMap.putIfAbsent method in Java?
EnumMapis similar toMap, except thatEnumMaponly takes theEnumtype as key. Also, all the keys must be from a single enum type. For further details, refer here.
The putIfAbsent method adds the key-value pair to the EnumMap object if the key is not present in the map. If the key is already present, then it skips the operation.
Syntax
public V putIfAbsent(K key,V value)
If the key is already present in the map, then the value associated with the key is returned, and no insertion will be done.
If the key is not present in the map, then the key-value pair is inserted, and null is returned.
The
nullreturn can also denote that the map previously associated thenullvalue with a key.
Code
The code below demonstrates how to use the putIfAbsent 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.println("The map is => " + map);System.out.println("\nTrying to add (Subject.MATHS, 10)");Integer value = map.putIfAbsent(Subject.MATHS, 10);// key - MATHS is already present in the map// so the value associated with the key is returnedSystem.out.println("The value is => " + value);System.out.println("\nTrying to add (Subject.ECONIMICS, 80)");value = map.putIfAbsent(Subject.ECONOMICS, 80);// key - ECONOMICS is not present// so a new entry will be added and null is returnedSystem.out.println("The value is => " + value);System.out.println("The map is => " + map);}}
In the code above, we:
-
Created an
Enumfor the Subjects with the nameSubject. -
Created an
EnumMapwith the namemap. -
Added three entries to the
map. -
We use the
putIfAbsentmethod to add a new entry to theEnumMapwith:- The already
existing key Subject.MATHS. In this case, the old value will be returned, and the insertion will be skipped. - The new
key Subject.ECONOMICS. In this case, the new key-value entry will be inserted, andnullis returned.
- The already