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()EnumSetEnumMap
- An
is a bit vector. For an enum with up to 64 constants it is a singleEnumSet , where bit n means "the constant with ordinal n is in the set" (thelong class). Larger enums use an array ofRegularEnumSet (long ).JumboEnumSet ,add andcontains are single bit operations, andremove orcontainsAll combine whole words at once.retainAll - An
is an array indexed by ordinal, holding one value slot per constant. There is no hashing, no collision handling and no entry objects.EnumMap
Both iterate in declaration order, whatever order elements were added in. Both reject nullClass
| Method | Since | Creates |
|---|---|---|
EnumSet.of(a, b, ...) | Java 5 | A set of the given constants |
EnumSet.noneOf(Type.class)allOf | Java 5 | An empty set, or every constant |
EnumSet.range(from, to) | Java 5 | Constants from fromto |
EnumSet.complementOf(set) | Java 5 | Every constant not in set |
EnumSet.copyOf(collection) | Java 5 | A copy; fails on an empty non-EnumSet collection |
new EnumMap<>(Type.class) | Java 5 | An empty map for that enum |
new EnumMap<>(map) | Java 5 | A 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, ADMINrangeDayOfWeekjava.time
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:
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]
includes both ends, so an editor has three permissions. It depends on declaration order, so reordering the enum changes what it means.range(READ, DELETE) gives every constant andallOf everything except the given ones, without listing them. Adding a new constant to the enum automatically includes it.complementOf answers "can an editor share?" with one bit test.contains- 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.
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:
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
on anmerge 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.EnumMap withgroupingBy as the map factory collects the order IDs per status into an() -> new EnumMap<>(Status.class) instead of aEnumMap . TheHashMapgroupingBy page covers the collector.- A lookup table of display labels per status is a natural
. For data that never changes, a field on the enum itself is often simpler.EnumMap - A
key throwsnull .NullPointerException
Implementation, ordering and flag bits
The program prints which class EnumSet
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:
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
backed by oneRegularEnumSet ; an enum with 66 constants needs more than 64 bits and gets along . The choice is automatic and invisible to callers.JumboEnumSet - Converting a set to
bits withint turned the editor's three permissions into binary 111, decimal 7, which fits in one database column;1 << ordinal() turns it back into a set. This replaces the C-stylefromBits 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.int - Both the set and the map iterate in declaration order:
added first still came afterADMIN .READ of an emptyEnumSet.copyOf throwsArrayList , because there is no element to tell it which enum type to use. UseIllegalArgumentException plusEnumSet.noneOf(Type.class) when the source may be empty.addAll
How much faster are they?
The program counts five million colour values in a HashMapEnumMapcontainsHashSetEnumSet
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):
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
counter was close to twice as fast as theEnumMap : an array index replaces hashing and bucket lookup.HashMap - For
, the difference was small, becausecontains with enum keys is already fast; enum hash codes are cheap and there are no collisions in such a small set.HashSet - The larger gain is memory. A
creates an entry object per key and a table of buckets, while anHashMap needs one array, and anEnumMap of up to 64 constants is a singleEnumSet inside one small object.long
Traps: null, empty copies and iteration
EnumSet and EnumMap behave like any SetMap
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:
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
is not an enum constant, so it has no slot or bit.null andput(null, ...) threwadd(null) , while the lookupsNullPointerException andget(null) simply answeredcontains(null) andnull . Code moving from afalse that used aHashMap key needs a real constant, such asnull , instead.UNKNOWN of an emptyEnumSet.copyOf andList threwnew EnumMap<>(emptyHashMap) : with no element to look at, they cannot find out the enum type. Copying an emptyIllegalArgumentException worked, because it carries its type. For collections that may be empty, start fromEnumSet and callEnumSet.noneOf(Size.class) .addAll- Removing
during a for-each loop did not throwL , and the loop still sawConcurrentModificationException . The iterator of a smallL 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.EnumSet follows theequals andSet contracts, so anMap equals aEnumMap with the same entries, and anHashMap equalsEnumSet with the same elements. Neither class is thread-safe; wrap them withSet.of orCollections.synchronizedMap when threads share them.synchronizedSet
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 EnumMapEnumSet
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:
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
throughNEW andPAID toSHIPPED , and each step was one array lookup plus one bit test.DELIVERED - Cancelling a shipped order was rejected with a message that lists the allowed next states,
, printed in declaration order.[DELIVERED] - The static block checks with
that every state has an entry. A developer who adds a new constant without transitions gets an error when the class loads, instead of acomplementOf at some laterNullPointerException .move - Questions about the whole machine are short loops over the table: the terminal states are those with an empty set,
andCANCELLED , their complement is the active states, andREFUNDED andPAID can lead to a refund.DELIVERED
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
| Situation | Use |
|---|---|
| A set of enum constants | EnumSetHashSet |
| A map with enum keys | EnumMap |
| Flags such as permissions or options | EnumSetint |
| Flags stored in a database or file | EnumSet |
| Grouping a stream by an enum | groupingBy(key, () -> new EnumMap<>(Type.class), ...) |
| Fixed data per constant | A field on the enum |
| A set or map shared between threads | Wrap with Collections.synchronizedSetsynchronizedMap |
For general set operations such as union and intersection, see