Reputation: 1133
I need to statically initialize an EnumMap. I know two ways.
Using of() method of Map
private static final Map<<EnumKey>, <Value>> TEST_MAP = Map.of(ENUM_CONST1, "Value1", ENUM_CONST2, "Value2");
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?
Upvotes: 13
Views: 15572
Reputation: 15136
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);
Upvotes: 16
Reputation: 140326
Do it in a method:
private static final EnumMap<....> yourMap = yourMapMethod();
private static EnumMap<....> yourMapMethod() {
EnumMap<....> yourMap = ...
yourMap.put(....);
yourMap.put(....);
return yourMap;
}
Upvotes: 2
Reputation: 120858
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
.
Upvotes: 3