Video in progress
When do you use EnumMap and EnumSet instead of a plain HashMap/HashSet?
Whenever the key is an enum, almost always. EnumMap uses a plain array indexed by the enum's ordinal() inside, and EnumSet uses a bit vector: no hash computation, little memory, and iteration in the order the enum is declared.
📖 Answer
enum Status { NEW, PAID, SHIPPED, CANCELLED }
Map<Status, Long> counts = new EnumMap<>(Status.class);
for (Order o : orders) {
counts.merge(o.status(), 1L, Long::sum);
}
Set<Status> finished = EnumSet.of(Status.SHIPPED, Status.CANCELLED);
if (finished.contains(order.status())) { ... }
For an enum with up to 64 values, an EnumSet fits into a single long (RegularEnumSet), and contains is a single bit check. With more than that you get JumboEnumSet, which uses a long[].
Useful factory methods: EnumSet.allOf, noneOf, range(NEW, PAID), complementOf(finished).
You can use it with streams too:
Map<Status, List<Order>> byStatus = orders.stream()
.collect(Collectors.groupingBy(Order::status,
() -> new EnumMap<>(Status.class), Collectors.toList()));
Limitations: no null keys, and not thread-safe. As a bonus, the output order is always the order the enum was declared in, which is handy in logs and reports.
Sign up to mark studied questions and save your progress.