Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Mapping Enum Keys With EnumMaps [Snippets]

DZone's Guide to

Mapping Enum Keys With EnumMaps [Snippets]

We take a look at a specialized way to create maps that have enum types as keys. See how to create and use EnumMaps and consider their benefits.

· Java Zone ·
Free Resource

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

Here’s a type that has been around in the JDK for a while and that comes in handy when we want to define maps with enum types as keys: An EnumMap is a specialized Map.

We’ll create a map for a given enum:

public enum CoffeeType {
    ESPRESSO, POUR_OVER, FRENCH_PRESS
}


The EnumMap needs to be aware of the enum class at creation time:

Map<CoffeeType, String> favoriteCoffeeOrigins = new EnumMap<>(CoffeeType.class);

favoriteCoffeeOrigins.put(CoffeeType.ESPRESSO, "Ethiopia");
favoriteCoffeeOrigins.put(CoffeeType.POUR_OVER, "Colombia");
favoriteCoffeeOrigins.put(CoffeeType.FRENCH_PRESS, "Indonesia");

assertThat(favoriteCoffeeOrigins.get(CoffeeType.ESPRESSO)).isEqualTo("Ethiopia");


An EnumMap is much more efficient compared to a HashMap implementation. All basic map operations of this Java implementation are executed in constant time.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,enum key ,enummaps

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}