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.

EnumMap is similar to Map, except that EnumMap only takes the Enum type 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 key already has a value, then the new value is updated and the old value is returned.

  • If there was no mapping for the key, then null is 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 Enum for the subjects with the name Subject.

  • We created an EnumMap with the name map.

  • We added three entries to the map.

  • We used the replace method to replace the value of the key Subject.MATHS with the value 10. This method will check if there is any mapping for the key Subject.MATHS. In our case, the key is associated with the value 50. So, the new value 10 is updated for the key Subject.MATHS, and the old value is returned.

  • We used the replace method to replace the value of the key Subject.ECONOMICS with the value 10. This method will check if there is any mapping for the key Subject.ECONOMICS. In our case, the key has no mapping, so null will be returned.

Free Resources