EnumMap class in Java

06 Dec, 2021
EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. It belongs to java.util package. A few important features of EnumMap are as follows: 
EnumMap class is a member of the Java Collections Framework & is not synchronized.
EnumMap is an ordered collection and they are maintained in the natural order of their keys(the natural order of keys means the order on which enum constants are declared inside enum type )
It’s a high-performance map implementation, much faster than HashMap.
All keys of each EnumMap instance must be keys of a single enum type.
EnumMap doesn’t allow null key and throws NullPointerException when we attempt to insert the null key.
Iterators returned by the collection views are weakly consistent: they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress.
EnumMap is internally represented as arrays. This representation is extremely compact and efficient.
Syntax: Declaration
public class EnumMap<K extends Enum<K>,​V> extends AbstractMap<K,​V> implements Serializable, Cloneable
Parameters:
Key object type
Value object type
K must extend Enum, which enforces the requirement that the keys must be of the specified enum type. 
EnumMap(Class keyType): The constructor is used to create an empty EnumMap with the specified keyType.EnumMap(EnumMap m): The constructor is used to create an enum map with the same keyType as the specified enum map, with initial mappings being the same as the EnumMapEnumMap(Map m): The constructor is used to create an enum map with initialization from the specified map in the parameter.
EnumMap(Class keyType): The constructor is used to create an empty EnumMap with the specified keyType.
EnumMap(EnumMap m): The constructor is used to create an enum map with the same keyType as the specified enum map, with initial mappings being the same as the EnumMap
EnumMap(Map m): The constructor is used to create an enum map with initialization from the specified map in the parameter.
Example  
Java
// Java Program to illustrate Working of EnumMap class// and its functions // Importing EnumMap classimport java.util.EnumMap; // Main classpublic class EnumMapExample {     // Enum    public enum GFG {        CODE,        CONTRIBUTE,        QUIZ,        MCQ;    }     // Main driver method    public static void main(String args[])    {         // Java EnumMap        // Creating an empty EnumMap with key        // as enum type state        EnumMap<GFG, String> gfgMap            = new EnumMap<GFG, String>(GFG.class);         // Putting values inside EnumMap in Java        // Inserting Enum keys different from        // their natural order        gfgMap.put(GFG.CODE, "Start Coding with gfg");        gfgMap.put(GFG.CONTRIBUTE, "Contribute for others");        gfgMap.put(GFG.QUIZ, "Practice Quizes");        gfgMap.put(GFG.MCQ, "Test Speed with Mcqs");         // Printing size of EnumMap        System.out.println("Size of EnumMap in java: "                           + gfgMap.size());         // Printing Java EnumMap        // Print EnumMap in natural order        // of enum keys (order on which they are declared)        System.out.println("EnumMap: " + gfgMap);         // Retrieving value from EnumMap        System.out.println("Key : " + GFG.CODE + " Value: "                           + gfgMap.get(GFG.CODE));         // Checking if EnumMap contains a particular key        System.out.println(            "Does gfgMap has " + GFG.CONTRIBUTE + ": "            + gfgMap.containsKey(GFG.CONTRIBUTE));         // Checking if EnumMap contains a particular value        System.out.println(            "Does gfgMap has :" + GFG.QUIZ + " : "            + gfgMap.containsValue("Practice Quizes"));        System.out.println("Does gfgMap has :" + GFG.QUIZ                           + " : "                           + gfgMap.containsValue(null));    }}
Size of EnumMap in java: 4
EnumMap: {CODE=Start Coding with gfg, CONTRIBUTE=Contribute for others, QUIZ=Practice Quizes, MCQ=Test Speed with Mcqs}
Key : CODE Value: Start Coding with gfg
Does gfgMap has CONTRIBUTE: true
Does gfgMap has :QUIZ : true
Does gfgMap has :QUIZ : false
Operation 1: Adding Elements
In order to add elements to the EnumMap, we can use put() or putAll() method as shown below.
Java
// Java Program to Add Elements to the EnumMap // Importing EnumMap classimport java.util.EnumMap; // Main class// AddingElementsToEnumMapclass GFG {     enum Color { RED, GREEN, BLUE, WHITE }    public static void main(String[] args)    {         // Creating an EnumMap of the Color enum        EnumMap<Color, Integer> colors1            = new EnumMap<>(Color.class);         // Insert elements in Map        // using put() method        colors1.put(Color.RED, 1);        colors1.put(Color.GREEN, 2);         // Printing mappings to the console        System.out.println("EnumMap colors1: " + colors1);         // Creating an EnumMap of the Color Enum        EnumMap<Color, Integer> colors2            = new EnumMap<>(Color.class);         // Adding elements using the putAll() method        colors2.putAll(colors1);        colors2.put(Color.BLUE, 3);         // Printing mappings to the console        System.out.println("EnumMap colors2: " + colors2);    }}
EnumMap colors1: {RED=1, GREEN=2}
EnumMap colors2: {RED=1, GREEN=2, BLUE=3}
 Operation 2: Accessing the Elements
We can access the elements of EnumMap using entrySet(), keySet(), values(), get(). The example below explains these methods.
Java
// Java Program to Access the Elements of EnumMap // Importing required classesimport java.util.EnumMap; // Main class// AccessElementsOfEnumMapclass GFG {     // Enum    enum Color { RED, GREEN, BLUE, WHITE }     // Main driver method    public static void main(String[] args)    {         // Creating an EnumMap of the Color enum        EnumMap<Color, Integer> colors            = new EnumMap<>(Color.class);         // Inserting elements using put() method        colors.put(Color.RED, 1);        colors.put(Color.GREEN, 2);        colors.put(Color.BLUE, 3);        colors.put(Color.WHITE, 4);         System.out.println("EnumMap colors : " + colors);         // Using the entrySet() method        System.out.println("Key/Value mappings: "                           + colors.entrySet());         // Using the keySet() method        System.out.println("Keys: " + colors.keySet());         // Using the values() method        System.out.println("Values: " + colors.values());         // Using the get() method        System.out.println("Value of RED : "                           + colors.get(Color.RED));    }}
EnumMap colors : {RED=1, GREEN=2, BLUE=3, WHITE=4}
Key/Value mappings: [RED=1, GREEN=2, BLUE=3, WHITE=4]
Keys: [RED, GREEN, BLUE, WHITE]
Values: [1, 2, 3, 4]
Value of RED : 1
Operation 3: Removing elements
In order to remove the elements, EnumMap provides two variations of the remove() method.
Example
Java
// Java program to Remove Elements of EnumMap // Importing EnumMap classimport java.util.EnumMap; // Main classclass GFG {     // Enum    enum Color {         // Custom elements        RED,        GREEN,        BLUE,        WHITE    }     // Main driver method    public static void main(String[] args)    {         // Creating an EnumMap of the Color enum        EnumMap<Color, Integer> colors            = new EnumMap<>(Color.class);         // Inserting elements in the Map        // using put() method        colors.put(Color.RED, 1);        colors.put(Color.GREEN, 2);        colors.put(Color.BLUE, 3);        colors.put(Color.WHITE, 4);         // Printing colors in the EnumMap        System.out.println("EnumMap colors : " + colors);         // Removing a mapping        // using remove() Method        int value = colors.remove(Color.WHITE);         // Displaying the removed value        System.out.println("Removed Value: " + value);         // Removing specific color and storing boolean        // if removed or not        boolean result = colors.remove(Color.RED, 1);         // Printing the boolean result whether removed or        // not        System.out.println("Is the entry {RED=1} removed? "                           + result);         // Printing the updated Map to the console        System.out.println("Updated EnumMap: " + colors);    }}
EnumMap colors : {RED=1, GREEN=2, BLUE=3, WHITE=4}
Removed Value: 4
Is the entry {RED=1} removed? true
Updated EnumMap: {GREEN=2, BLUE=3}
Operation 4: Replacing elements
Map interface provides three variations of the replace() method to change the mappings of EnumMap.
Example
Java
// Java Program to Replace Elements of EnumMap // Importing required classesimport java.util.EnumMap; // Main classclass GFG {     // Enum    enum Color {         RED,        GREEN,        BLUE,        WHITE    }     // Main driver method    public static void main(String[] args)    {         // Creating an EnumMap of the Color enum        EnumMap<Color, Integer> colors            = new EnumMap<>(Color.class);         // Inserting elements to Map        // using put() method        colors.put(Color.RED, 1);        colors.put(Color.GREEN, 2);        colors.put(Color.BLUE, 3);        colors.put(Color.WHITE, 4);         // Printing all elements inside above Map        System.out.println("EnumMap colors " + colors);         // Replacing certain elements depicting colors        // using the replace() method        colors.replace(Color.RED, 11);        colors.replace(Color.GREEN, 2, 12);         // Printing the updated elements (colors)        System.out.println("EnumMap using replace(): "                           + colors);         // Replacing all colors using the replaceAll()        // method        colors.replaceAll((key, oldValue) -> oldValue + 3);         // Printing the elements of above Map        System.out.println("EnumMap using replaceAll(): "                           + colors);    }}
EnumMap colors {RED=1, GREEN=2, BLUE=3, WHITE=4}
EnumMap using replace(): {RED=11, GREEN=12, BLUE=3, WHITE=4}
EnumMap using replaceAll(): {RED=14, GREEN=15, BLUE=6, WHITE=7}
The implementation of an EnumMap is not synchronized. This means that if multiple threads access a tree set concurrently, and at least one of the threads modifies the set, it must be synchronized externally. This is typically accomplished by using the synchronizedMap() method of the Collections class. This is best done at the creation time, to prevent accidental unsynchronized access. 
 Map<EnumKey, V> m = Collections.synchronizedMap(new EnumMap<EnumKey, V>(...));
K – Type of the key object
V – Type of the value object
Method
Action Performed 
Method
Description
Method
Descriptionenter 
Property
EnumMap
EnumSet
This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on GeeksforGeek’s main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
Chinmoy Lenka
Ganeshchowdharysadanala
prasannachalluri
solankimayank
Java-Collections
Java-EnumMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Split() String method in Java with examples
Object Oriented Programming (OOPs) Concept in Java
For-each loop in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java