Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

EnumMap

A map whose keys are values of one enum. Fast, and keeps keys in declaration order.

Available since: Java 5

Syntax

public class EnumMap<K extends Enum<K>, V> extends AbstractMap<K, V>

Parameters

ParameterTypeDescription
keyTypeClass<K>The enum class of the keys, for example Day.class (passed to the constructor).

Examples

Keys follow the order in which the constants are declared, not the insertion order:

enum Day { MON, TUE, WED }
 
void main() {
    Map<Day, String> plan = new EnumMap<>(Day.class);
    plan.put(Day.WED, "gym");
    plan.put(Day.MON, "work");
 
    IO.println(plan);
    IO.println(plan.containsKey(Day.TUE));
}

Output:

{MON=work, WED=gym}
false

Counting orders by status with groupingBy into an EnumMap:

enum Status { NEW, PAID, SHIPPED }
 
record Order(int id, Status status) {}
 
void main() {
    List<Order> orders = List.of(
        new Order(1, Status.PAID),
        new Order(2, Status.NEW),
        new Order(3, Status.PAID));
 
    Map<Status, Long> counts = orders.stream()
        .collect(Collectors.groupingBy(Order::status,
            () -> new EnumMap<>(Status.class), Collectors.counting()));
    IO.println(counts);
}

Output:

{NEW=1, PAID=2}

Notes

Inside an EnumMap is a plain array indexed by the constant's ordinal(), so it is faster and leaner than a HashMap. A null key is not allowed (NullPointerException); null values are fine. The constructor needs the enum class because, due to type erasure, the collection would not otherwise know which constants exist. You can copy an ordinary map: new EnumMap<>(map).

See also

  • EnumSet — A set of values of one enum. Works like a set of bit flags, but with readable code.
  • Enum.values() — Methods of every enum: values() gives all constants, valueOf() finds one by name, ordinal() and name() give its index and name.
  • HashMap — A map backed by a hash table: fast lookup by key, no guaranteed order.
  • enum — Declares an enum — a type with a fixed set of values.
  • Collectors.groupingBy() — A collector that sorts elements into groups that share a key.

Related recipes

In the tutorial

  • Collections for enums — EnumMap and EnumSet in Java: a map and a set for enum constants, ranges and complements, values(), valueOf() and why you should not rely on ordinal().

Thanks for reading!

Donate to the site — we work hard for you.