What is the best way to statically initialize an EnumMap in Java
Asked Answered
C

3

10

I need to statically initialize an EnumMap. I know two ways.

  1. Using of() method of Map

    private static final Map<<EnumKey>, <Value>> TEST_MAP = Map.of(ENUM_CONST1, "Value1", ENUM_CONST2, "Value2");
    
  2. Using double brace initialization

    private static final Map<<EnumKey>, <Value>> TEST_MAP = new EnumMap<>(EnumKey.class) {
        {
            put(ENUM_CONST1, "Value1");
            put(ENUM_CONST2, "Value2");
         }
    };
    

Is there any other cleaner and more efficient way?

Closehauled answered 19/5, 2021 at 16:41 Comment(1)
second one is a big anti-pattern and your first one does not initialize an EnumMap, but a Map (immutable one)Annettaannette
D
15

A neat way to setup EnumMap is to define all the values in-line using Map.of or Map.ofEntries but note that this allocates a Map before the EnumMap constructor:

private static final EnumMap<YourEnum,String> A = new EnumMap<>(Map.of(
        YourEnum.ONE, "Value1",
        YourEnum.TWO, "Value2"
));

// Use Map.ofEntries for enums with more than 10 values:
private static final EnumMap<YourEnum,String> B = new EnumMap<>(Map.ofEntries(
        Map.entry(YourEnum.ONE, "Value1"),
        Map.entry(YourEnum.TWO, "Value2")
));

If wanting public access then wrap as unmodifiable Map (which is backed by EnumMap) or just pass back Map.of directly (but is not using an EnumMap).

public static final Map<YourEnum,String> C = Collections.unmodifiableMap(B);
Deraign answered 20/5, 2021 at 11:48 Comment(0)
A
3

do it in a static block:

private static final EnumMap<....> yourMap = ...

static {
   yourMap.put(....);
   yourMap.put(....)
}

There will be ways to do this rather differently (but they don't exist in the API yet), via Constant Dynamic.

Annettaannette answered 19/5, 2021 at 16:46 Comment(7)
any specific reason of doing it in static block?Hawkinson
@Hawkinson how else?Annettaannette
the first one also looks good. Is it better to do with static blockHawkinson
Thanks got the answer. "Note that this Map.of method supports only a maximum of 10 key-value pairs." mention it in your article - baeldung.com/java-initialize-hashmapHawkinson
yeah agree...I was talking about Map.of which can store max of 10 mapping which is overcome with the ofEntriesHawkinson
@Hawkinson A specific reason to use it could be to only have access to Java 8. Map.of() was introduced with Java 9.Rockrose
hmm, static block or static method is the only way to do it in java 8Hawkinson
G
2

Do it in a method:

private static final EnumMap<....> yourMap = yourMapMethod();

private static EnumMap<....> yourMapMethod() {
   EnumMap<....> yourMap = ...
   yourMap.put(....);
   yourMap.put(....);
   return yourMap;
}
Gorey answered 19/5, 2021 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.