Effective Java: EnumMap
To support storing data as key-value format, Java has many implementation ofMap such as HashMap, IdentityHashMap, LinkedHashMap, TreeMap,etc. All of these Map allow keys to be of arbitrary object type; even null is allowed to be used as key.
EnumMap is a specialized Map implementation for use exclusively with an Enum type keys. Consequently, unlike other maps, EnumMap doesn’t permit null keys.
Lets discuss Enum ordinal. For an enum type such as follows :
enum MessageFlag{
DEBUG, INFO, WARNING, ERROR
}Java compiler generates an associated ordinal value for each declared constant according to its position in the declaration, accessible by ordinal() function, where the initial constant is assigned an ordinal of zero.
DEBUG | INFO | WARNING | ERROR
0 1 2 3System.out.println(MessageFlag.WARNING.ordinal()); // prints 2We can useEnumMap for this MessageFlag enum to create a color mapping for each flag type:
EnumMap<MessageFlag, String> colorMap = new EnumMap<>(MessageFlag.class);
colorMap.put(MessageFlag.INFO, "blue");
colorMap.put(MessageFlag.WARNING, "amber");
colorMap.put(MessageFlag.ERROR, "red");
colorMap.put(MessageFlag.DEBUG, "grey");As shown in the initialization step, we must provide the Enum type we intend to use (MessageFlag) as key for the map.
Get Rashed Alam’s stories in your inbox
Join Medium for free to get updates from this writer.
EnumMap is represented internally as arrays and its keys are naturally ordered according to the ordinal value of each constant. Following example demonstrates this with EnumMap.keySet() function:
Object[] keyArr = colorMap.keySet().toArray();
System.out.println(keyArr[2]); // prints WARNINGAnother important property of EnumMap is, unlike HashMap/TreeMap it’s iterators returned by collection views(keySet(), entrySet(), and values()) are weekly consistent: won’t throw ConcurrentModificationException and any concurrent modifications may/may not be reflected while the iteration in progress.
Thread itrThread = new Thread(()->{
// AsyncUtil.uncheckedSleep(700);
colorMap.keySet().forEach(key -> {
AsyncUtil.uncheckedSleep(2000);
System.out.printf("ITR-THREAD: (%s => %s)\n", key, colorMap.remove(key));
});
});itrThread.start();// an utility that uncheck InterruptedException of Thread.sleep :)
AsyncUtil.uncheckedSleep(100);
colorMap.remove(MessageFlag.DEBUG); // removing value for DEBUG
AsyncUtil.uncheckedSleep(200);
colorMap.remove(MessageFlag.WARNING); // removing value for WARNING
If you notice the printed message carefully from above you will see it prints mapping of DEBUG mapped value as DEBUG => nulland doesn’t print mapping for WARNING . The reason is lambda captured the local key before the main thread could remove it in case of DEBUG.
These two properties make EnumMap compact and efficient for case of ordinal index based time-costly computations on large dataset. For example: lets say we have large list of restaurants List<Restaurant> and we want to calculate sales count by RestaurantType Enum. Using EnumMap<ResturantType, Integer> to do the computation will be lot faster and safe from concurrent modification exception; even though it might not be able to capture data modification in real-time.
Another use case I have found for EnumMap is when I want to do functional mapping for well-defined data type. For example if for a service, incoming data types are string and I were to write a type resolver mapping from String to Specific type:
enum DataTypes
{
Integer, Long, Instant
}
EnumMap<DataTypes, TypeResolver> resolverMap = new EnumMap<>(DataTypes.class);
resolverMap.put(DataTypes.Long, TypeResolvers.longResolver());
// other mappingsStatically typed language always helps writing better code that can work as living documentation along with runtime type safety and performance. EnumMap is just another example of these effective features :).









