Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
EnumMap put() Method in Java with Examples
Next article icon

EnumMap Class in Java

Last Updated : 19 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

  • The EnumMap class is a member of the Java Collections Framework and 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 in which enum constants are declared inside the 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 a 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.

Example: This example demonstrates adding elements to an EnumMap and printing them.

Java
// Java Program to demonstrate  // the working of EnumMap  import java.util.EnumMap;  enum Day {     MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }  public class Geeks {     public static void main(String[] args) {                  // Create an EnumMap for Day enum         EnumMap<Day, String> dayMap = new EnumMap<>(Day.class);          // Add elements to the EnumMap         dayMap.put(Day.MONDAY, "Start of the week");         dayMap.put(Day.FRIDAY, "End of the week");         dayMap.put(Day.SUNDAY, "Weekend");          // Print all elements in the EnumMap         for (Day day : dayMap.keySet()) {             System.out.println(day + ": " + dayMap.get(day));         }     } } 

Output
MONDAY: Start of the week FRIDAY: End of the week SUNDAY: Weekend 

EnumMap Hierarchy

EnumMapInJava


Declaration of EnumMap

In Java, the declaration of EnumMap can be done as:

EnumMap<EnumType, ValueType> map = new EnumMap<>(EnumType.class);

Note: EnumType is the type of the enum that will be used as keys in the map and ValueType is the type of the values associated with the enum keys.

The EnumMap class in Java is a specialized map implementation that is designed specifically for use with enum keys. An EnumMap is a compact, efficient, and fast alternative to using a HashMap with enum keys.

Example: This example demonstrates how to use an EnumMap in Java to store and retrieve values associated with enum keys.

Java
// EnumMap to store and retrive  // values associated with enum constants import java.util.EnumMap; enum Days {     MONDAY,     TUESDAY,     WEDNESDAY,     THURSDAY,     FRIDAY,     SATURDAY,     SUNDAY }  public class Geeks {     public static void main(String[] args)     {         EnumMap<Days, String> e = new EnumMap<>(Days.class);          // Adding elements to the EnumMap         e.put(Days.MONDAY, "Work");         e.put(Days.TUESDAY, "Work");         e.put(Days.WEDNESDAY, "Study");         e.put(Days.THURSDAY, "Study");         e.put(Days.FRIDAY, "Relax");          // Getting elements from the EnumMap         System.out.println(e.get(Days.MONDAY));         System.out.println(e.get(Days.FRIDAY));     } } 

Output
Work Relax 

Explanation: In this example, we define an enum type Days that represents the days of the week. We then create an EnumMap and add elements to it using the put method. Finally, we retrieve elements from the EnumMap using the get method and print the results to the console.

Constructors

Constructor

Description

EnumMap(Class keyType)

This constructor is used to create an empty EnumMap with the specified keyType.

EnumMap(EnumMap m)

This 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)

This constructor is used to create an enum map with initialization from the specified map in the parameter.


Example: This example demonstrates how to create, perform basic operation such as size, retrieval and check for keys and values on an EnumMap.

Java
// Java Program to create, perform basic operation import java.util.EnumMap;  public class Geeks {      // Defining an enum called GFG     public enum GFG {         CODE,         CONTRIBUTE,         QUIZ,         MCQ     }      public static void main(String[] args) {          // Creating an EnumMap where the key is          // of type GFG and the value is a String         EnumMap<GFG, String> e = new EnumMap<>(GFG.class);          // Adding key-value pairs to the map         e.put(GFG.CODE, "Start Coding with GFG");         e.put(GFG.CONTRIBUTE, "Contribute for others");         e.put(GFG.QUIZ, "Practice Quizzes");         e.put(GFG.MCQ, "Test Speed with MCQs");          // Printing the size of the EnumMap         System.out.println("Size of EnumMap: " + e.size());          // Printing the contents of the EnumMap         // The map will print in the natural order of          // enum keys (the order in which they are defined)         System.out.println("EnumMap: " + e);          // Retrieving a value from the EnumMap using a specific key         System.out.println("Value for CODE: " + e.get(GFG.CODE));          // Checking if the EnumMap contains a specific key         System.out.println("Does gfgMap contain CONTRIBUTE? "          + e.containsKey(GFG.CONTRIBUTE));          // Checking if the EnumMap contains a specific value         System.out.println("Does gfgMap contain the value 'Practice Quizzes'? "          + e.containsValue("Practice Quizzes"));          // Checking if the EnumMap contains a null value          // (which is not present in this example)         System.out.println("Does gfgMap contain a null value? "          + e.containsValue(null));     } } 

Output:

Output

Performing Various Operations on LinkedTransferQueue

1. Adding Elements: We can use put() and putAll() method to insert elements to a EnumMap.

Example: This example demonstrates how to add elements to an EnumMap using put() and putAll() methods.

Java
// Java Program to add elements to an EnumMap import java.util.EnumMap;  class Geeks {      enum Color { RED, GREEN, BLUE, WHITE }     public static void main(String[] args)     {         // Creating an EnumMap of the Color enum         EnumMap<Color, Integer> e                 = new EnumMap<>(Color.class);          // Insert elements in Map         // using put() method         e.put(Color.RED, 1);         e.put(Color.GREEN, 2);          // Printing mappings to the console         System.out.println("EnumMap colors1: " + e);          // Creating an EnumMap of the Color Enum         EnumMap<Color, Integer> e1                 = new EnumMap<>(Color.class);          // Adding elements using the putAll() method         e1.putAll(e);         e1.put(Color.BLUE, 3);          // Printing mappings to the console         System.out.println("EnumMap colors2: " + e1);     } } 

Output
EnumMap colors1: {RED=1, GREEN=2} EnumMap colors2: {RED=1, GREEN=2, BLUE=3} 


2. Accessing Elements: We can use entrySet(), keySet(), values() and get() to access the elements of EnumMap.

Example: This example demonstrates how to access elements of an EnumMap using methods like entrySet(), keySet(), values() and get().

Java
// Java Program to Access the Elements of EnumMap import java.util.EnumMap; class Geeks {          // Enum     enum Color { RED, GREEN, BLUE, WHITE }      public static void main(String[] args)     {         // Creating an EnumMap of the Color enum         EnumMap<Color, Integer> e                 = new EnumMap<>(Color.class);          // Inserting elements using put() method         e.put(Color.RED, 1);         e.put(Color.GREEN, 2);         e.put(Color.BLUE, 3);         e.put(Color.WHITE, 4);          System.out.println("EnumMap: " + e);          // Using the entrySet() method         System.out.println("Key-Value mappings: "                 + e.entrySet());          // Using the keySet() method         System.out.println("Keys: " + e.keySet());          // Using the values() method         System.out.println("Values: " + e.values());          // Using the get() method         System.out.println("Value of RED : "                 + e.get(Color.RED));     } } 

Output
EnumMap: {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 


3. Removing Elements: We can use the remove() method to remove elements from the EnumMap.

Example: This example demonstrates how to remove elements from an EnumMap using remove() and the conditional remove(key,value) method.

Java
// Java program to Remove Elements of EnumMap import java.util.EnumMap; class Geeks {      enum Color {          // Custom elements         RED,         GREEN,         BLUE,         WHITE     }     public static void main(String[] args)     {          // Creating an EnumMap of the Color enum         EnumMap<Color, Integer> e                 = new EnumMap<>(Color.class);          // Inserting elements in the Map         // using put() method         e.put(Color.RED, 1);         e.put(Color.GREEN, 2);         e.put(Color.BLUE, 3);         e.put(Color.WHITE, 4);          // Printing e in the EnumMap         System.out.println("EnumMap e : " + e);          // Removing a mapping         // using remove() Method         int i = e.remove(Color.WHITE);          // Displaying the removed value         System.out.println("Removed Value: " + i);          // Removing specific color and storing boolean         // if removed or not         boolean b = e.remove(Color.RED, 1);          // Printing the boolean result whether removed or         // not         System.out.println("Is the entry {RED=1} removed? "                 + b);          // Printing the updated Map to the console         System.out.println("Updated EnumMap: " + e);     } } 

Output
EnumMap e : {RED=1, GREEN=2, BLUE=3, WHITE=4} Removed Value: 4 Is the entry {RED=1} removed? true Updated EnumMap: {GREEN=2, BLUE=3} 


4. Replacing Elements: Map interface provides three variations of the replace() method to change the mappings of EnumMap.

Example: This example demonstrates how to replace elements in an EnumMap using replace(), conditional replace(key, oldValue, newValue), and replaceAll() method.

Java
// Java Program to Replace Elements of EnumMap  import java.util.EnumMap;  class Geeks {          enum Color {          RED,         GREEN,         BLUE,         WHITE     }     public static void main(String[] args)     {          // Creating an EnumMap of the Color enum          EnumMap<Color, Integer> e                 = new EnumMap<>(Color.class);          // Inserting elements to Map          // using put() method          e.put(Color.RED, 1);         e.put(Color.GREEN, 2);         e.put(Color.BLUE, 3);         e.put(Color.WHITE, 4);          // Printing all elements inside above Map          System.out.println("EnumMap e " + e);          // Replacing certain elements depicting e          // using the replace() method          e.replace(Color.RED, 11);         e.replace(Color.GREEN, 2, 12);          // Printing the updated elements (e)          System.out.println("EnumMap using replace(): "                 + e);          // Replacing all e using the replaceAll()          // method          e.replaceAll((key, oldValue) -> oldValue + 3);          // Printing the elements of above Map          System.out.println("EnumMap using replaceAll(): "                 + e);     } } 

Output
EnumMap e {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} 

Synchronized EnumMap

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>(…));

Advantages

  • Efficient: The EnumMap class provides fast and efficient access to elements stored in the map, making it a good choice for use in performance-critical applications.
  • Compact: The EnumMap class uses a compact representation for the map, which means that it requires less memory than a HashMap or a TreeMap.
  • Type-safe: The EnumMap class only allows keys of a specified enum type, which means that it provides type-safe behavior and eliminates the need for casting.
  • Sorted keys: The EnumMap class provides sorted keys, which means that the elements in the map are ordered by the order in which the enum constants are declared.

Disadvantages

  • Limited to enum keys: The EnumMap class can only be used with keys of an enum type, which means that it’s not suitable for use with other types of keys.
  • Immutable keys: The EnumMap class uses enum keys, which are immutable and cannot be modified once they are created.

Methods

Method

Action Performed 

clear()Removes all mappings from this map.
clone()Returns a shallow copy of this enum map.
containsKey?(Object key)Returns true if this map contains a mapping for the specified key.
containsValue?(Object value)Returns true if this map maps one or more keys to the specified value.
entrySet()Returns a Set view of the mappings contained in this map.
equals?(Object o)Compares the specified object with this map for equality.
get?(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
hashCode()Returns the hash code value for this map.
keySet()Returns a Set view of the keys contained in this map.
put?(K key, V value)Associates the specified value with the specified key in this map.
putAll?(Map<? extends K,?? extends V> m)Copies all of the mappings from the specified map to this map.
remove?(Object key)Removes the mapping for this key from this map if present.
size()Returns the number of key-value mappings in this map.
values()Returns a Collection view of the values contained in this map.

Methods Declared in AbstractMap Class

Method

Description

isEmpty()Returns true if this map contains no key-value mappings.
toString()Returns a string representation of this map.

Methods Declared in Interface java.util.Map

Method

Descriptionenter 

compute?(K key, BiFunction<? super K,?? super V,?? extends V> remappingFunction)Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping).
 computeIfAbsent?(K key, Function<? super K,?? extends V> mappingFunction)If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
 computeIfPresent?(K key, BiFunction<? super K,?? super V,?? extends V> remappingFunction)If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
 forEach?(BiConsumer<? super K,?? super V> action)Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.
getOrDefault?(Object key, V defaultValue)Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
merge?(K key, V value, BiFunction<? super V,?? super V,?? extends V> remappingFunction)If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value.
putIfAbsent?(K key, V value)If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
remove?(Object key, Object value)Removes the entry for the specified key only if it is currently mapped to the specified value.
replace?(K key, V value)Replaces the entry for the specified key only if it is currently mapped to some value.
replace?(K key, V oldValue, V newValue)Replaces the entry for the specified key only if currently mapped to the specified value.
replaceAll?(BiFunction<? super K,?? super V,?? extends V> function)Replaces each entry’s value with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

EnumMap vs EnumSet

Property

EnumMap

EnumSet

Internal RepresentationEnumMap is internally represented as arrays. The representation is compact and efficient.EnumSet is internally represented as BitVector or sequence of bits.
Permits Null Elements?Null keys are not allowed but Null values are allowed.Null elements are not permitted.
Is the Abstract Class?NoYes
InstantiationSince EnumMap is not an abstract class, it can be instantiated using the new operator.It is an abstract class, it does not have a constructor. Enum set is created using its predefined methods like allOf(), noneOf(), of(), etc.
ImplementationEnumMap is a specialized Map implementation for use with enum type keys.EnumSet is a specialized Set implementation for use with enum types.


Next Article
EnumMap put() Method in Java with Examples

P

Pratik Agarwal
Improve
Article Tags :
  • Java
  • Java-Collections
  • Java-EnumMap
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • EnumMap Class in Java
    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: The EnumMap class is a member of the Java Collections Framework an
    12 min read
  • EnumMap put() Method in Java with Examples
    The Java.util.EnumMap.put() method in Java associates specified key-value pairs. In simple words, the put() method is used to add or modify entries in the EnumMap. If the values are repeated, the older values are replaced. Example Java Code // Java Program to demonstrate the usage of EnumMap import
    4 min read
  • EnumMap putAll(map) Method in Java
    The Java.util.EnumMap.putAll(map) method in Java is used to copy all the mappings from one map to a newer one. Older mappings are replaced in a newer one. Syntax: void putAll(map) Parameters: The method takes one parameter map. It is the map which is to be copied to the newer one. Return Value The m
    2 min read
  • EnumMap values() Method in Java
    The Java.util.EnumMap.values() method in Java is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the EnumMap. Syntax: EnumMap.values() Parameters: The method does not take any argument. Return Values: The method returns the collection
    2 min read
  • EnumMap remove() Method in Java
    The Java.util.EnumMap.remove(key) method in Java is used to remove the specified key from the map. Syntax: remove(Object key) Parameters: The method takes one parameter key which refers to the key whose mapping is to be removed. Return Value: The method does not return any value. Below programs illu
    2 min read
  • EnumMap clone() Method in Java
    The Java.util.EnumMap.clone() method in Java is used to copy the mapped values of one map to another. It basically creates a shallow copy of this map. Syntax: Enum_map_2 = Enum_map_1.clone() Parameters: The method does not accept any argument. Return Value: The method returns a shallow copy of a Enu
    2 min read
  • EnumMap entrySet() Method in Java
    The Java.util.EnumMap.entrySet() method in Java used to create a set out of the elements contained in the EnumMap. It basically returns a set view of the enum map. Syntax: enum_map.entrySet() Parameter: The method does not take any parameters. Return Value: The method returns the set view of mapping
    2 min read
  • EnumMap clear() Method in Java with Examples
    The Java.util.EnumMap.clear() method in Java is used to remove all the mappings from the map. The method does not delete the map instead it just clears the map of the mappings. Syntax: enum_map.clear() Parameters: This method does not accept any argument. Return Values: This method does not return a
    2 min read
  • EnumMap equals() Method in Java with Examples
    The Java.util.EnumMap.equals(obj) in Java is used to compare the passed object with this EnumMap for the equality. It must be kept in mind that the object passed must be a map of the same type as the EnumMap.Syntax: boolean equals(Object obj) Parameter: The method takes one parameter obj of Object t
    2 min read
  • EnumMap size() Method in Java
    The Java.util.EnumMap.size() method in java is used to know the size of the map or the number of elements present in the map. Syntax: Enum_Map.size() Parameters: The method does not take any parameters. Return Value: The method returns the size of the map. Below programs illustrate the working of si
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences