EnumMap in Java

In this article, we will learn all about EnumMap in Java. What is EnumMap and how to use it with examples?

What will we Learn?

  1. EnumMap Class Overview
  2. EnumMap Class Constructor Summary
  3. EnumMap Class Method Summary
  4. EnumMap Class Examples

1. EnumMap Class Overview

Like most collection implementations EnumMap is not synchronized. If multiple threads access an enum map concurrently, and at least one of the threads modifies the map, it should be synchronized externally. 
Example:
     Map<EnumKey, V> m
         = Collections.synchronizedMap(new EnumMap<EnumKey, V>(...));

Properties of EnumMap Class

  1. All keys used in EnumMap must be from same Enum type which is specified while creating EnumMap in Java. For example, if you can not use different enum instances from two different enums.
  2. EnumMap is an ordered collection and they are maintained in the natural order of their keys( natural order of keys means the order on which enum constant are declared inside enum type ). you can verify this while Iterating over an EnumMap in Java.
  3. Iterators of EnumMap are fail-fast Iterator, much like of ConcurrentHashMap and doesn't throw ConcurrentModificationException and may not show an effect of any modification on EnumMap during Iteration process.
  4. You can not insert null keys inside EnumMap in Java. EnumMap doesn't allow null key and throws NullPointerException, at same time null values are permitted.
  5. EnumMap is not synchronized and it has to be synchronized manually before using it in a concurrent or multi-threaded environment. like synchronized Map, in Java, you can also make EnumMap synchronized by using Collections.synchronizedMap() method and as per Javadoc this should be done while creating EnumMap in java to avoid accidental non synchronized access.
  6. EnumMap likely gives a better performance than HashMap in Java. So prefer EnumMap if you are going to use enum keys.

2. EnumMap Class Constructor Summary

  • EnumMap(Class keyType) - Creates an empty enum map with the specified key type.
  • EnumMap(EnumMap<K,? extends V> m) - Creates an enum map with the same key type as the specified enum map, initially containing the same mappings (if any).
  • EnumMap(Map<K,? extends V> m) - Creates an enum map initialized from the specified map.

3. EnumMap Class Method Summary


  • void clear() - This method removes all mappings from this map.
  • EnumMap<K,V> clone() - This method returns a shallow copy of this enum map.
  • boolean containsKey(Object key) - This method returns true if this map contains a mapping for the specified key.
  • boolean containsValue(Object value) - This method returns true if this map maps one or more keys to the specified value.
  • Set<Map.Entry<K,V>> entrySet() - This method returns a Set view of the mappings contained in this map.
  • boolean equals(Object o) - This method compares the specified object with this map for equality.
  • V get(Object key) - This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
  • int hashCode() - This method returns the hash code value for this map.
  • Set keySet() - This method returns a Set view of the keys contained in this map.
  • V put(K key, V value) - This method associates the specified value with the specified key in this map.
  • void putAll(Map<? extends K,? extends V> m) - This method copies all of the mappings from the specified map to this map.
  • V remove(Object key) - This method removes the mapping for this key from this map if present.
  • int size() - This method returns the number of key-value mappings in this map.
  • Collection values() - This method returns a Collection view of the values contained in this map.

4. EnumMap Class Examples

Simple Days Enum Example

In this example, we will use Days enum with all predefined days as keys in EnumMap:
import java.util.EnumMap;
import java.util.Map.Entry;

/**
 * EnumMap Demonstration Example
 * @author Ramesh Fadatare
 *
 */
public class EnumMapExample {
     enum Days {
         SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
     }

     public static void main(final String[] args) {
         final EnumMap<Days, String> enumMap = new EnumMap<>(Days.class);
         enumMap.put(Days.SUNDAY, "Its Sunday!!");
         enumMap.put(Days.MONDAY, "Its Monday!!");
         enumMap.put(Days.TUESDAY, "Its Tuesday!!");
         enumMap.put(Days.WEDNESDAY, "Its Wednesday!!");
         enumMap.put(Days.THURSDAY, "Its Thursday!!");
         enumMap.put(Days.FRIDAY, "Its Friday!!");
         enumMap.put(Days.SATURDAY, "Its Saturday!!");
  
         for(final Entry<Days, String> entry : enumMap.entrySet()){
             System.out.println(" Key -> " + entry.getKey().SUNDAY);
             System.out.println("Value - >" + entry.getValue());
         }
     }
}
Output:
 Key -> SUNDAY
Value - >Its Sunday!!
 Key -> SUNDAY
Value - >Its Monday!!
 Key -> SUNDAY
Value - >Its Tuesday!!
 Key -> SUNDAY
Value - >Its Wednesday!!
 Key -> SUNDAY
Value - >Its Thursday!!
 Key -> SUNDAY
Value - >Its Friday!!
 Key -> SUNDAY
Value - >Its Saturday!!

Real world Example

As we know that every project has list status as a project is active, inactive, close, start etc. Let's create a ProjectStatus Enum which acts as key against each project. Let's demonstrate this with an example:
import java.util.EnumMap;
import java.util.Map.Entry;

/**
 * EnumMap Demonstration Example
 * @author Ramesh Fadatare
 *
 */
public class EnumMapExample2 {
    public static void main(final String[] args) {
        final EnumMap<ProjectStatus, Project> enumMap = new EnumMap<>(ProjectStatus.class);
        enumMap.put(ProjectStatus.ACTIVE, new Project(100, "Customer Management System", "Customer Management System"));
        enumMap.put(ProjectStatus.INACTIVE,
        new Project(200, "Employee Management System", "Employee Management System"));

        for (final Entry<ProjectStatus, Project> entry : enumMap.entrySet()) {
            final ProjectStatus projectStatus = entry.getKey();
            System.out.println(" Key -> " + projectStatus.name());
            final Project project = entry.getValue();
            System.out.println("Value - >" + project.toString());
       }
 }

   enum ProjectStatus {
      ACTIVE, INACTIVE
   }
}

class Project {
    private int id;
    private String name;
    private String desc;

    public Project(final int id, final String name, final String desc) {
        super();
        this.id = id;
        this.name = name;
        this.desc = desc;
    }

    public int getId() {
        return id;
    }

    public void setId(final int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public String getDesc() {
       return desc;
    }

    public void setDesc(final String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return "[project id : " + this.id + ", project name : "
                + this.name + ", project desc : " + this.desc + " ]";
    }
}
Output:
 Key -> ACTIVE
Value - >[project id : 100, project name : Customer Management System, project desc : Customer Management System ]
 Key -> INACTIVE
Value - >[project id : 200, project name : Employee Management System, project desc : Employee Management System ]

Related Collections Examples

Reference

Comments

  1. This is not true "3. Iterators of EnumMap are fail-fast Iterator... " . Iterators are weakly consistent. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/EnumMap.html

    ReplyDelete

Post a Comment

Leave Comment