Core Java

Mapping enum keys with EnumMaps

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 such as 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.

This post was reposted from my newsletter issue 017.

Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Mapping enum keys with EnumMaps

Opinions expressed by Java Code Geeks contributors are their own.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Sebastian Daschner

Sebastian Daschner is a self-employed Java consultant and trainer. He is the author of the book 'Architecting Modern Java EE Applications'. Sebastian is a Java Champion, Oracle Developer Champion and JavaOne Rockstar.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button