EnumMap in Java

Naveen AnamaneniUpdated · 3 min read

EnumMap in Java is a specialized Map implementation whose keys are constants of a single enum type. It is used to link a value to each enum constant, for example a working-hours count to each day of the week. Inside, EnumMap stores its values in a simple array indexed by the enum constant's position, so it is extremely fast and compact. In this lesson, you will learn how to create and use an EnumMap.

Declaration

Declaration
public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V>
        implements Serializable, Cloneable

Features of EnumMap

  • Keys from one enum type only.
  • Declaration order: entries always come out in the order the constants are declared.
  • No null keys; null values are allowed.
  • Very fast: get and put are simple array accesses.
  • Not synchronized.

Constructors

ConstructorDescription
EnumMap(Class<K> keyType)It creates an empty map for the given enum type.
EnumMap(EnumMap<K, ? extends V> m)It creates a copy of another EnumMap.
EnumMap(Map<K, ? extends V> m)It creates an EnumMap from another map (which must have at least one key).

Example: Hours Worked per Day

Let's see an example that stores hours for each working day.

EnumMapDemo.java▶ Try it
import java.time.DayOfWeek;
import java.util.EnumMap;
import java.util.Map;
 
public class EnumMapDemo {
    public static void main(String[] args) {
        Map<DayOfWeek, Integer> hours = new EnumMap<>(DayOfWeek.class);
        hours.put(DayOfWeek.FRIDAY, 6);
        hours.put(DayOfWeek.MONDAY, 8);
        hours.put(DayOfWeek.WEDNESDAY, 7);
        System.out.println(hours);
 
        int total = 0;
        for (int h : hours.values()) {
            total += h;
        }
        System.out.println("Total: " + total + " hours");
        System.out.println("Tuesday: "
            + hours.getOrDefault(DayOfWeek.TUESDAY, 0));
    }
}
Output
{MONDAY=8, WEDNESDAY=7, FRIDAY=6}
Total: 21 hours
Tuesday: 0

Explanation: The days were added as Friday, Monday, Wednesday, but the map prints them in the order they are declared in DayOfWeek. The constructor needs the enum's class, DayOfWeek.class, so the map knows how big its internal array must be.

Example: Counting by Status

StatusCount.java▶ Try it
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
 
public class StatusCount {
    enum Status { PENDING, SHIPPED, DELIVERED, CANCELLED }
 
    public static void main(String[] args) {
        List<Status> orders = List.of(Status.SHIPPED, Status.PENDING,
            Status.SHIPPED, Status.DELIVERED, Status.SHIPPED);
 
        Map<Status, Integer> counts = new EnumMap<>(Status.class);
        for (Status s : Status.values()) {
            counts.put(s, 0);
        }
        for (Status s : orders) {
            counts.merge(s, 1, Integer::sum);
        }
        System.out.println(counts);
    }
}
Output
{PENDING=1, SHIPPED=3, DELIVERED=1, CANCELLED=0}

Explanation: Every status starts at 0, then merge adds 1 for each order. The result lists all statuses in declaration order, including CANCELLED with 0.

Common Mistakes

Forgetting the class argument: new EnumMap<>(). It doesn't compile; pass Type.class.

Putting a null key. It throws NullPointerException.

Creating an EnumMap from an empty plain map. The type can't be determined, so it throws IllegalArgumentException.

Practice

  1. Easy: Create an enum Planet with four planets and an EnumMap from each planet to its number of moons. Print the map.
  2. Harder: Given a list of Size values (S, M, L, XL) from orders, count each size with an EnumMap and print the most ordered size.

Quick check: EnumMap

4 questions
1What type of keys can an EnumMap have?
2In what order are EnumMap entries printed?
3What does the EnumMap constructor need?
4How does EnumMap store values internally?

Key Takeaways

Was this tutorial helpful?

Lesson 292 of 482