Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

EnumMap → Java EnumMap


Java EnumMap


EnumMap is a specialized implementation of the Map interface designed specifically for working with enum (enumeration) values as keys. It offers a memory-efficient and type-safe way to store key-value pairs where the keys are restricted to a single enum type.

Characteristics of EnumMap

Enum-Based Keys: Keys in EnumMap must be from a single, specified enum type. This enforces type safety and prevents accidental usage of non-enum keys. Efficiency: EnumMap uses a compact internal representation based on an array. This leads to efficient storage and retrieval of key-value pairs compared to general-purpose Maps like HashMap. Thread-Safety: EnumMap is thread-safe, meaning it can be used in concurrent environments without extra synchronization.

Initializing and Declaring EnumMap

Enummap Declaration EnumMap<EnumType, ValueType> mapName;
EnumMap: This specifies the class you're using. <EnumType, ValueType>: Placeholders for the enum type used for keys and the data type for values. mapName: The name for your reference variable.
Initialization: There are two main ways to initialize an EnumMap: Creating an empty EnumMap:
Creating empty EnumMap EnumMap<DayOfWeek, String> activityPlan = new EnumMap<>(DayOfWeek.class);
This approach directly creates an empty EnumMap with the specified enum type (DayOfWeek) for keys.
Creating an EnumMap with Initial Values (Constructor with EnumMap argument):
Creating an EnumMap with Initial Values EnumMap<Color, String> colorMeanings = new EnumMap<>(Enum.mapOf( Color.RED, "Passion", Color.GREEN, "Growth", Color.BLUE, "Tranquility" ));
This approach uses a constructor that takes another EnumMap as an argument. You can create a temporary EnumMap using Enum.mapOf() to provide initial key-value pairs.
Adding Key-Value Pairs: The put(K key, V value) method is used to add key-value pairs to the EnumMap. However, the key must be of the enum type specified during initialization. Simple example of using EnumMap
EnumMap simple example in java import java.util.*; enum DayOfWeek {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY} public class Main { public static void main(String[] args) { EnumMap<DayOfWeek, String> activityPlan = new EnumMap<>(DayOfWeek.class); activityPlan.put(DayOfWeek.MONDAY, "Gym workout"); activityPlan.put(DayOfWeek.WEDNESDAY, "Team meeting"); activityPlan.put(DayOfWeek.FRIDAY, "Movie night"); System.out.println(activityPlan.get(DayOfWeek.FRIDAY)); System.out.println(activityPlan.get(DayOfWeek.TUESDAY)); } }


Movie night null
In this example, an EnumMap is used to store activity plans for each day of the week (represented by the DayOfWeek enum).
Map from existing Map
Using EnumMap from another EnumMap Map<EnumType, ValueType> anotherMap = ...; // Existing Map with compatible key and value types myMap = EnumMap.copyOf(anotherMap);

Common EnumMap Methods (similar to HashMap):

put(key, value): Inserts a new key-value pair into the map. get(key): Returns the value associated with the given key, or null if the key doesn't exist. containsKey(key): Checks if the map contains a specific key. remove(key): Removes the key-value pair associated with the given key and returns the value. isEmpty(): Checks if the map is empty. size(): Returns the number of key-value pairs in the map.

Examples for EnumMap

Translating Month Numbers to Names
Month names to number using java EnumMap import java.util.*; enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER } public class Main { public static void main(String[] args) { EnumMap<Month, Integer> monthNames = new EnumMap<>(Month.class); monthNames.put(Month.JANUARY, 1); monthNames.put(Month.FEBRUARY, 2); monthNames.put(Month.MARCH, 3); System.out.println(monthNames.get(Month.MARCH)); System.out.println(monthNames.get(Month.JUNE)); } }


3 null
Explanation : This example uses an EnumMap to map month numbers (represented by the Month enum) to their corresponding names. This provides a clear and type-safe way to translate between numeric month values and their textual representations.
Weekday Statistics with EnumMap
Weekday statistics using Java EnumMap import java.util.*; enum Weekday {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY} public class Main { public static void main(String[] args) { EnumMap<Weekday, Integer> stats =new EnumMap<>(Weekday.class); stats.put(Weekday.MONDAY, 10); stats.put(Weekday.WEDNESDAY, 15); int tuesdayStats = stats.get(Weekday.MONDAY); System.out.println("Tuesday stats: " + tuesdayStats); boolean hasSundayStats = stats.containsKey(Weekday.FRIDAY); System.out.println("Has Sunday stats: " + hasSundayStats); } }


Tuesday stats: 10 Has Sunday stats: false
Explanation : This example uses an EnumMap to update stats to their corresponding days.
Storing Game Character Stats (Using Custom Enum):
EnumMap example with getter and setter in java import java.util.EnumMap; enum Attribute { STRENGTH, DEXTERITY, INTELLIGENCE, CONSTITUTION, CHARISMA } class GameCharacter { String name; EnumMap<Attribute, Integer> stats; public GameCharacter(String name) { = name; this.stats = new EnumMap<>(Attribute.class); } public void setStat(Attribute attribute, int value) { stats.put(attribute, value); } public int getStat(Attribute attribute) { return stats.get(attribute); } } public class Main { public static void main(String[] args) { GameCharacter warrior = new GameCharacter("Bruenor"); warrior.setStat(Attribute.STRENGTH, 18); warrior.setStat(Attribute.DEXTERITY, 14); System.out.println(warrior.getStat(Attribute.STRENGTH)); } }


This example defines a custom Attribute enum to represent various character attributes in a game. An EnumMap is used within the GameCharacter class to store the character's stats (strength, dexterity, etc.) associated with the corresponding enum values. This approach ensures type safety and clarity when accessing and modifying character stats.
Mapping Traffic Signal States to Descriptions
Traffic signal - EnumMap example in java import java.util.EnumMap; enum TrafficSignal { RED, YELLOW, GREEN } public class Main { public static void main(String[] args) { EnumMap<TrafficSignal, String> signalDescriptions = new EnumMap<>(TrafficSignal.class); signalDescriptions.put(TrafficSignal.RED, "Stop"); signalDescriptions.put(TrafficSignal.YELLOW, "Caution"); signalDescriptions.put(TrafficSignal.GREEN, "Go"); System.out.println(signalDescriptions.get(TrafficSignal.YELLOW)); } }


Explanation : This example uses an EnumMap to map traffic signal states (represented by the TrafficSignal enum) to their descriptive meanings ("Stop", "Caution", "Go"). This provides a convenient way to interpret the current traffic signal state based on the enum value.
Note : Remember, EnumMap is a versatile tool for storing key-value pairs where the keys are guaranteed to be from a specific enum type. It offers efficiency and type safety when working with enums in Java collections. Key Points to Remember: ⮞ EnumMap is ideal for scenarios where keys are guaranteed to be enums. ⮞ It offers performance and memory benefits compared to HashMap for enum-based keys. ⮞ The enum type used for keys must be specified during initialization. ⮞ Null keys are not allowed in EnumMap. ⮞ By understanding EnumMap, you can leverage its efficiency and type safety when working with enums as keys in your Java collections. It's a valuable tool for situations where you need a map specifically designed for enum-based key management.