EnumSet and EnumMap

When the elements of a set or the keys of a map are enum constants, EnumSet and EnumMap are smaller and faster than HashSet and HashMap. They use the fact that an enum has a fixed, numbered list of constants. This page explains how they store data, runs the factory methods, converts flag sets to integers and back, shows grouping into an EnumMap, and measures the gain.

Contents

How EnumSet and EnumMap store enums

Every enum constant has an ordinal(), its position in the declaration starting at 0, and the set of constants never changes at run time. EnumSet and EnumMap, both added in Java 5, are built on that:

  • An EnumSet is a bit vector. For an enum with up to 64 constants it is a single long, where bit n means "the constant with ordinal n is in the set" (the RegularEnumSet class). Larger enums use an array of long (JumboEnumSet). add, contains and remove are single bit operations, and containsAll or retainAll combine whole words at once.
  • An EnumMap is an array indexed by ordinal, holding one value slot per constant. There is no hashing, no collision handling and no entry objects.

Both iterate in declaration order, whatever order elements were added in. Both reject null keys or elements, and both are created for one specific enum type, which is why their factories take a Class argument.

EnumSet and EnumMap API
MethodSinceCreates
EnumSet.of(a, b, ...)Java 5A set of the given constants
EnumSet.noneOf(Type.class), allOfJava 5An empty set, or every constant
EnumSet.range(from, to)Java 5Constants from from to to, both included
EnumSet.complementOf(set)Java 5Every constant not in set
EnumSet.copyOf(collection)Java 5A copy; fails on an empty non-EnumSet collection
new EnumMap<>(Type.class)Java 5An empty map for that enum
new EnumMap<>(map)Java 5A copy of another map with enum keys

Each example on this page is a complete program run on JDK 21.

EnumSet: permissions and days

Permissions are a classic case for a set of flags. The declaration order READ, WRITE, DELETE, SHARE, ADMIN goes from weakest to strongest, which makes range meaningful. DayOfWeek from java.time is an enum too.

Java
import java.time.DayOfWeek;
import java.util.EnumSet;
import java.util.Set;

public class EnumSetDemo {

    enum Permission { READ, WRITE, DELETE, SHARE, ADMIN }

    public static void main(String[] args) {
        Set<Permission> viewer = EnumSet.of(Permission.READ);
        Set<Permission> editor = EnumSet.range(Permission.READ, Permission.DELETE);
        Set<Permission> everything = EnumSet.allOf(Permission.class);
        Set<Permission> notAdmin = EnumSet.complementOf(EnumSet.of(Permission.ADMIN));

        System.out.println("viewer:     " + viewer);
        System.out.println("editor:     " + editor);
        System.out.println("everything: " + everything);
        System.out.println("notAdmin:   " + notAdmin);
        System.out.println("editor can share? " + editor.contains(Permission.SHARE));

        // Elements always come out in declaration order, whatever order you add them
        Set<DayOfWeek> meetings = EnumSet.noneOf(DayOfWeek.class);
        meetings.add(DayOfWeek.FRIDAY);
        meetings.add(DayOfWeek.MONDAY);
        meetings.add(DayOfWeek.WEDNESDAY);
        System.out.println("meetings:   " + meetings);

        Set<DayOfWeek> weekend = EnumSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY);
        System.out.println("weekdays:   " + EnumSet.complementOf(EnumSet.copyOf(weekend)));
    }
}

Output:

Output
viewer:     [READ]
editor:     [READ, WRITE, DELETE]
everything: [READ, WRITE, DELETE, SHARE, ADMIN]
notAdmin:   [READ, WRITE, DELETE, SHARE]
editor can share? false
meetings:   [MONDAY, WEDNESDAY, FRIDAY]
weekdays:   [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY]
  • range(READ, DELETE) includes both ends, so an editor has three permissions. It depends on declaration order, so reordering the enum changes what it means.
  • allOf gives every constant and complementOf everything except the given ones, without listing them. Adding a new constant to the enum automatically includes it.
  • contains answers "can an editor share?" with one bit test.
  • Meetings added in a mixed order are printed in week order, because iteration follows the ordinal. Weekdays are simply the complement of the weekend.

EnumMap: counting, grouping and lookup tables

Order statuses are a typical enum key: a fixed set of states, with something to count or store for each one.

Java
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class EnumMapDemo {

    enum Status { NEW, PAID, SHIPPED, DELIVERED, CANCELLED }

    record Order(int id, Status status) {
    }

    public static void main(String[] args) {
        List<Order> orders = List.of(
                new Order(1, Status.SHIPPED), new Order(2, Status.NEW),
                new Order(3, Status.SHIPPED), new Order(4, Status.DELIVERED),
                new Order(5, Status.NEW));

        // Count per status; keys print in declaration order, not insertion order
        Map<Status, Integer> counts = new EnumMap<>(Status.class);
        for (Order o : orders) {
            counts.merge(o.status(), 1, Integer::sum);
        }
        System.out.println("counts:  " + counts);

        // groupingBy into an EnumMap
        Map<Status, List<Integer>> ids = orders.stream()
                .collect(Collectors.groupingBy(Order::status,
                        () -> new EnumMap<>(Status.class),
                        Collectors.mapping(Order::id, Collectors.toList())));
        System.out.println("ids:     " + ids);

        // A lookup table keyed by every constant
        Map<Status, String> labels = new EnumMap<>(Status.class);
        for (Status s : Status.values()) {
            labels.put(s, s.name().charAt(0) + s.name().substring(1).toLowerCase());
        }
        System.out.println("labels:  " + labels.values());

        try {
            counts.put(null, 0);
        } catch (NullPointerException e) {
            System.out.println("null key: NullPointerException");
        }
    }
}

Output:

Output
counts:  {NEW=2, SHIPPED=2, DELIVERED=1}
ids:     {NEW=[2, 5], SHIPPED=[1, 3], DELIVERED=[4]}
labels:  [New, Paid, Shipped, Delivered, Cancelled]
null key: NullPointerException
  • merge on an EnumMap counts orders per status, and the result is printed in the order the statuses are declared, a natural order for reports. Statuses with no orders are simply absent.
  • groupingBy with () -> new EnumMap<>(Status.class) as the map factory collects the order IDs per status into an EnumMap instead of a HashMap. The groupingBy page covers the collector.
  • A lookup table of display labels per status is a natural EnumMap. For data that never changes, a field on the enum itself is often simpler.
  • A null key throws NullPointerException.

Implementation, ordering and flag bits

The program prints which class EnumSet chose for a small and a large enum, converts a permission set to an integer bit mask and back, and checks the ordering rules.

Java
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;

public class Internals {

    enum Permission { READ, WRITE, DELETE, SHARE, ADMIN }

    // An enum with more than 64 constants
    enum Big {
        C0, C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, C11, C12, C13, C14, C15, C16, C17, C18, C19,
        C20, C21, C22, C23, C24, C25, C26, C27, C28, C29, C30, C31, C32, C33, C34, C35, C36, C37,
        C38, C39, C40, C41, C42, C43, C44, C45, C46, C47, C48, C49, C50, C51, C52, C53, C54, C55,
        C56, C57, C58, C59, C60, C61, C62, C63, C64, C65
    }

    // Store a set of flags as one int, for example in a database column
    static int toBits(Set<Permission> set) {
        int bits = 0;
        for (Permission p : set) {
            bits |= 1 << p.ordinal();
        }
        return bits;
    }

    static EnumSet<Permission> fromBits(int bits) {
        EnumSet<Permission> set = EnumSet.noneOf(Permission.class);
        for (Permission p : Permission.values()) {
            if ((bits & (1 << p.ordinal())) != 0) {
                set.add(p);
            }
        }
        return set;
    }

    public static void main(String[] args) {
        // EnumSet picks an implementation by the number of constants
        System.out.println("5 constants:  "
            + EnumSet.noneOf(Permission.class).getClass().getSimpleName());
        System.out.println("66 constants: " + EnumSet.noneOf(Big.class).getClass().getSimpleName());

        EnumSet<Permission> editor = EnumSet.of(Permission.READ, Permission.WRITE,
            Permission.DELETE);
        int bits = toBits(editor);
        System.out.println("editor as bits: " + Integer.toBinaryString(bits) + " = " + bits);
        System.out.println("back to a set:  " + fromBits(bits));

        // Iteration always follows declaration order, whatever the insertion order
        EnumSet<Permission> mixed = EnumSet.noneOf(Permission.class);
        mixed.add(Permission.ADMIN);
        mixed.add(Permission.READ);
        System.out.println("insertion ADMIN, READ -> " + mixed);

        // EnumMap keys are kept in declaration order too
        Map<Permission, String> owners = new EnumMap<>(Permission.class);
        owners.put(Permission.SHARE, "bob");
        owners.put(Permission.READ, "ann");
        System.out.println("EnumMap order: " + owners);

        // Copying from an empty ordinary collection needs the element type
        try {
            EnumSet.copyOf(new java.util.ArrayList<Permission>());
        } catch (IllegalArgumentException e) {
            System.out.println("EnumSet.copyOf(empty list): IllegalArgumentException");
        }
    }
}

Output:

Output
5 constants:  RegularEnumSet
66 constants: JumboEnumSet
editor as bits: 111 = 7
back to a set:  [READ, WRITE, DELETE]
insertion ADMIN, READ -> [READ, ADMIN]
EnumMap order: {READ=ann, SHARE=bob}
EnumSet.copyOf(empty list): IllegalArgumentException
  • A five-constant enum gets a RegularEnumSet backed by one long; an enum with 66 constants needs more than 64 bits and gets a JumboEnumSet. The choice is automatic and invisible to callers.
  • Converting a set to int bits with 1 << ordinal() turned the editor's three permissions into binary 111, decimal 7, which fits in one database column; fromBits turns it back into a set. This replaces the C-style int flag constants that older Java code used, while keeping storage compact. Stored bits depend on declaration order, so new constants must be added at the end.
  • Both the set and the map iterate in declaration order: ADMIN added first still came after READ.
  • EnumSet.copyOf of an empty ArrayList throws IllegalArgumentException, because there is no element to tell it which enum type to use. Use EnumSet.noneOf(Type.class) plus addAll when the source may be empty.

How much faster are they?

The program counts five million colour values in a HashMap and an EnumMap, then makes five million contains checks on a HashSet and an EnumSet, keeping the fastest of three runs.

Java
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;

public class SpeedCheck {

    enum Color { RED, ORANGE, YELLOW, GREEN, BLUE, INDIGO, VIOLET }

    static final Color[] ALL = Color.values();

    public static void main(String[] args) {
        int n = 5000000;
        System.out.printf("%,d counter updates%n", n);
        timeMap("HashMap", () -> new HashMap<>(), n);
        timeMap("EnumMap", () -> new EnumMap<>(Color.class), n);

        Set<Color> hashSet = new HashSet<>(Set.of(Color.RED, Color.GREEN, Color.BLUE));
        Set<Color> enumSet = EnumSet.of(Color.RED, Color.GREEN, Color.BLUE);
        System.out.printf("%,d contains() checks%n", n);
        timeSet("HashSet", hashSet, n);
        timeSet("EnumSet", enumSet, n);
    }

    static void timeMap(String name, Supplier<Map<Color, Integer>> factory, int n) {
        long best = Long.MAX_VALUE;
        for (int run = 0; run < 3; run++) {
            Map<Color, Integer> counts = factory.get();
            long t0 = System.nanoTime();
            for (int i = 0; i < n; i++) {
                counts.merge(ALL[i % ALL.length], 1, Integer::sum);
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("  %-8s %6.1f ms%n", name, best / 1e6);
    }

    static void timeSet(String name, Set<Color> set, int n) {
        long best = Long.MAX_VALUE;
        int hits = 0;
        for (int run = 0; run < 3; run++) {
            hits = 0;
            long t0 = System.nanoTime();
            for (int i = 0; i < n; i++) {
                if (set.contains(ALL[i % ALL.length])) {
                    hits++;
                }
            }
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("  %-8s %6.1f ms  (%,d hits)%n", name, best / 1e6, hits);
    }
}

Output (a rough comparison from one 2-CPU Linux machine, JDK 21):

Output
5,000,000 counter updates
  HashMap    66.8 ms
  EnumMap    38.1 ms
5,000,000 contains() checks
  HashSet     9.7 ms  (2,142,858 hits)
  EnumSet     9.3 ms  (2,142,858 hits)
  • The EnumMap counter was close to twice as fast as the HashMap: an array index replaces hashing and bucket lookup.
  • For contains, the difference was small, because HashSet with enum keys is already fast; enum hash codes are cheap and there are no collisions in such a small set.
  • The larger gain is memory. A HashMap creates an entry object per key and a table of buckets, while an EnumMap needs one array, and an EnumSet of up to 64 constants is a single long inside one small object.

Traps: null, empty copies and iteration

EnumSet and EnumMap behave like any Set and Map most of the time, but their array and bit-vector storage shows through at the edges. The program tries each edge case on a four-constant enum and prints the result or the exception.

Java
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class EnumTraps {

    enum Size { S, M, L, XL }

    interface Attempt {
        Object run();
    }

    static void attempt(String label, Attempt a) {
        try {
            System.out.printf("%-44s -> %s%n", label, a.run());
        } catch (RuntimeException e) {
            System.out.printf("%-44s -> %s%n", label, e.getClass().getSimpleName());
        }
    }

    public static void main(String[] args) {
        // null is not an enum constant
        attempt("EnumMap.put(null, ...)", () -> new EnumMap<Size, Integer>(Size.class)
                .put(null, 1));
        attempt("EnumMap.get(null)", () -> new EnumMap<Size, Integer>(Size.class).get(null));
        attempt("EnumSet.of(Size.S).add(null)", () -> EnumSet.of(Size.S).add(null));
        attempt("EnumSet.of(Size.S).contains(null)", () -> EnumSet.of(Size.S).contains(null));

        // copyOf needs to know the enum type
        List<Size> none = new ArrayList<>();
        attempt("EnumSet.copyOf(empty List)", () -> EnumSet.copyOf(none));
        attempt("EnumSet.copyOf(empty EnumSet)", () -> EnumSet.copyOf(EnumSet.noneOf(Size.class)));
        attempt("new EnumMap<>(empty HashMap)", () -> new EnumMap<>(new HashMap<Size, Integer>()));

        // Iterators never throw ConcurrentModificationException
        EnumSet<Size> sizes = EnumSet.allOf(Size.class);
        List<Size> seen = new ArrayList<>();
        for (Size s : sizes) {
            seen.add(s);
            if (s == Size.S) {
                sizes.remove(Size.L);                           // change during iteration
            }
        }
        attempt("remove(L) while iterating, elements seen", () -> seen);

        // Equality works across implementations
        Map<Size, Integer> enumMap = new EnumMap<>(Map.of(Size.S, 1, Size.M, 2));
        Map<Size, Integer> hashMap = new HashMap<>(Map.of(Size.S, 1, Size.M, 2));
        attempt("EnumMap.equals(HashMap with same entries)", () -> enumMap.equals(hashMap));
        Set<Size> enumSet = EnumSet.of(Size.S, Size.M);
        attempt("EnumSet.equals(Set.of(S, M))", () -> enumSet.equals(Set.of(Size.S, Size.M)));
    }
}

Output:

Output
EnumMap.put(null, ...)                       -> NullPointerException
EnumMap.get(null)                            -> null
EnumSet.of(Size.S).add(null)                 -> NullPointerException
EnumSet.of(Size.S).contains(null)            -> false
EnumSet.copyOf(empty List)                   -> IllegalArgumentException
EnumSet.copyOf(empty EnumSet)                -> []
new EnumMap<>(empty HashMap)                 -> IllegalArgumentException
remove(L) while iterating, elements seen     -> [S, M, L, XL]
EnumMap.equals(HashMap with same entries)    -> true
EnumSet.equals(Set.of(S, M))                 -> true
  • null is not an enum constant, so it has no slot or bit. put(null, ...) and add(null) threw NullPointerException, while the lookups get(null) and contains(null) simply answered null and false. Code moving from a HashMap that used a null key needs a real constant, such as UNKNOWN, instead.
  • EnumSet.copyOf of an empty List and new EnumMap<>(emptyHashMap) threw IllegalArgumentException: with no element to look at, they cannot find out the enum type. Copying an empty EnumSet worked, because it carries its type. For collections that may be empty, start from EnumSet.noneOf(Size.class) and call addAll.
  • Removing L during a for-each loop did not throw ConcurrentModificationException, and the loop still saw L. The iterator of a small EnumSet works on a copy of the bit vector taken when it started, so changes made during the loop are not reflected. The Javadoc calls these iterators weakly consistent: they never throw, but do not promise to show changes.
  • equals follows the Set and Map contracts, so an EnumMap equals a HashMap with the same entries, and an EnumSet equals Set.of with the same elements. Neither class is thread-safe; wrap them with Collections.synchronizedMap or synchronizedSet when threads share them.

A state machine from an EnumMap of EnumSets

A table of allowed transitions is one of the best uses of the two classes together: an EnumMap from each state to the EnumSet of states it may move to. The order statuses below model a shop, where an order can be cancelled only before payment and refunded only after it.

Java
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class StateMachine {

    enum Status { NEW, PAID, SHIPPED, DELIVERED, CANCELLED, REFUNDED }

    // Allowed next states for every state, filled in once when the class loads
    static final Map<Status, Set<Status>> NEXT = new EnumMap<>(Status.class);

    static {
        NEXT.put(Status.NEW, EnumSet.of(Status.PAID, Status.CANCELLED));
        NEXT.put(Status.PAID, EnumSet.of(Status.SHIPPED, Status.REFUNDED));
        NEXT.put(Status.SHIPPED, EnumSet.of(Status.DELIVERED));
        NEXT.put(Status.DELIVERED, EnumSet.of(Status.REFUNDED));
        NEXT.put(Status.CANCELLED, EnumSet.noneOf(Status.class));
        NEXT.put(Status.REFUNDED, EnumSet.noneOf(Status.class));
        // Every state must have an entry: adding a constant without one fails at startup
        EnumSet<Status> missing = EnumSet.complementOf(EnumSet.copyOf(NEXT.keySet()));
        if (!missing.isEmpty()) {
            throw new IllegalStateException("no transitions for " + missing);
        }
    }

    static Status move(Status from, Status to) {
        if (!NEXT.get(from).contains(to)) {
            throw new IllegalStateException(from + " -> " + to + " is not allowed; allowed: "
                    + NEXT.get(from));
        }
        return to;
    }

    public static void main(String[] args) {
        Status s = Status.NEW;
        for (Status to : List.of(Status.PAID, Status.SHIPPED, Status.DELIVERED)) {
            s = move(s, to);
            System.out.println("moved to " + s);
        }
        try {
            move(Status.SHIPPED, Status.CANCELLED);
        } catch (IllegalStateException e) {
            System.out.println("rejected: " + e.getMessage());
        }

        // Derived sets, computed from the table
        EnumSet<Status> terminal = EnumSet.noneOf(Status.class);
        NEXT.forEach((state, next) -> {
            if (next.isEmpty()) {
                terminal.add(state);
            }
        });
        System.out.println("terminal states: " + terminal);
        System.out.println("still active:    " + EnumSet.complementOf(terminal));

        // Which states can reach REFUNDED in one step?
        EnumSet<Status> canRefund = EnumSet.noneOf(Status.class);
        NEXT.forEach((state, next) -> {
            if (next.contains(Status.REFUNDED)) {
                canRefund.add(state);
            }
        });
        System.out.println("can be refunded from: " + canRefund);
    }
}

Output:

Output
moved to PAID
moved to SHIPPED
moved to DELIVERED
rejected: SHIPPED -> CANCELLED is not allowed; allowed: [DELIVERED]
terminal states: [CANCELLED, REFUNDED]
still active:    [NEW, PAID, SHIPPED, DELIVERED]
can be refunded from: [PAID, DELIVERED]
  • The order moved from NEW through PAID and SHIPPED to DELIVERED, and each step was one array lookup plus one bit test.
  • Cancelling a shipped order was rejected with a message that lists the allowed next states, [DELIVERED], printed in declaration order.
  • The static block checks with complementOf that every state has an entry. A developer who adds a new constant without transitions gets an error when the class loads, instead of a NullPointerException at some later move.
  • Questions about the whole machine are short loops over the table: the terminal states are those with an empty set, CANCELLED and REFUNDED, their complement is the active states, and PAID and DELIVERED can lead to a refund.

The same shape fits permissions per role, features per subscription plan and valid actions per screen: any rule of the form "for each constant of one enum, a set of constants of another".

When to use them

Choosing a set or map for enum keys
SituationUse
A set of enum constantsEnumSet, never HashSet
A map with enum keysEnumMap
Flags such as permissions or optionsEnumSet, instead of int bit constants
Flags stored in a database or fileEnumSet in code, converted to bits or names at the edge
Grouping a stream by an enumgroupingBy(key, () -> new EnumMap<>(Type.class), ...)
Fixed data per constantA field on the enum
A set or map shared between threadsWrap with Collections.synchronizedSet or synchronizedMap; neither class is thread-safe

For general set operations such as union and intersection, see set operations.