What is the EnumMap.replace() method in Java?
In EnumMap, we can use the replace method to replace the value associated with the key. If there is no value associated with the key, then no action is performed.
EnumMapis similar toMap, except thatEnumMaponly takes theEnumtype as a key. All of the keys must also be from a single enum type. For further details, refer here.
Syntax
public V replace(K key, V value)
Arguments
key: The key for which the new value is to be updated.value: The new value to be updated.
Return value
-
If the
keyalready has a value, then the new value is updated and the old value is returned. -
If there was no mapping for the key, then
nullis returned.
Working example
The example below shows how to use the replace method.
import java.util.EnumMap;class Replace {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("\nCalling map.replace(Subject.MATHS, 10)");Integer returnValue = map.replace(Subject.MATHS, 10);System.out.println("Return value of Replace method: " + returnValue);System.out.println("\nThe map is: " + map );System.out.println("\nCalling map.replace(Subject.ECONOMICS, 10)");returnValue = map.replace(Subject.ECONOMICS, 10);System.out.println("The return value of the Replace method: " + returnValue);System.out.println("The map is: " + map );}}
Explanation
In the code above:
-
We created an
Enumfor the subjects with the nameSubject. -
We created an
EnumMapwith the namemap. -
We added three entries to the
map. -
We used the
replacemethod to replace the value of the keySubject.MATHSwith the value10. This method will check if there is any mapping for the keySubject.MATHS. In our case, the key is associated with the value50. So, the new value10is updated for the keySubject.MATHS, and the old value is returned. -
We used the
replacemethod to replace the value of the keySubject.ECONOMICSwith the value10. This method will check if there is any mapping for the keySubject.ECONOMICS. In our case, the key has no mapping, sonullwill be returned.