What is the EnumMap.put() method in Java?

EnumMap is similar to Map, except that EnumMap only takes the Enum type as a key. Additionally, all the keys in the EnumMap must be from a single Enum type.

The put() method of the EnumMap class:

  • Adds a new key-value mapping if there is no mapping already present for the passed key.

  • Updates the value of the key-value mapping if there is a mapping present for the passed key.

Syntax

public V put(K key,V value)

Parameters

  • key: This is the key for which the value is to be mapped.

  • value: This is the value that needs to be associated with the key.

Return value

If the key is already present in the hashtable, then the old value is replaced with the passed value, and the old value is returned.

If the key is not present in the map, a new key-value pair is inserted and null is returned.

Note: The null return can also indicate that the previous null value is associated with the passed key.

Code

The code below demonstrates how we can use the put() method:

import java.util.EnumMap;
class Gett {
enum Days{
MON, TUE, WED, THUR, FRI, SAT, SUN
};
public static void main( String args[] ) {
EnumMap<Days, String> map = new EnumMap<>(Days.class);
map.put(Days.MON, "chest");
System.out.println("The map is : " + map);
System.out.println("Adding the entry (Days.MON-'shoulder'). The return value is " + map.put(Days.MON, "shoulder"));
System.out.println("Adding the entry (Days.TUE-'leg'). The return value is " + map.put(Days.TUE, "leg"));
}
}

Explanation

  • Line 1: We import the EnumMap class.

  • Line 3: We create an Enum for the days of the week with the name Days.

  • Line 7: We create an EnumMap object with the name map.

  • Line 8: We use the put() method to add a mapping ({Days.MON="chest"}) to the map object.

  • Line 9: We use the put() method with the key Days.MON and the value shoulder. There is already another value mapped to the key Days.MON. Hence, the put() method will replace the old value (“chest”) with the new value (“shoulder”) and return the old value (“chest”).

  • Line 10: We use the put() method with the key Days.TUE and the value leg. There is no value mapped to the key Days.TUE. Hence, the put() method adds a new mapping, {Days.TUE - leg}, to the map.

Free Resources