Java EnumMap Example

EnumMap is a specialized Map implementation for use with enum type keys. It's part of the java.util package. Being both compact and efficient, the performance of EnumMap surpasses HashMap when the key is an enum type.

Key Points: 

Optimized for Enums: All keys in an EnumMap must come from a single enum type. 

Order: Keys are maintained in their natural order (the order in which the enum constants are declared). 

Nulls: While EnumMap does not allow null keys (because the key is an enum type), it does permit null values. 

Not Thread-Safe: EnumMap itself is not thread-safe. External synchronization is required if multiple threads modify an enum map concurrently and at least one of the threads modifies it.

Common Operations with EnumMap in Java

import java.util.EnumMap;

// Define an enumeration for colors
enum Color {
    RED, GREEN, BLUE
}

public class EnumMapDemo {
    public static void main(String[] args) {
        // 1. Initializing an empty EnumMap
        EnumMap<Color, String> colorMap = new EnumMap<>(Color.class);

        // 2. Putting values into EnumMap
        colorMap.put(Color.RED, "Apple");
        colorMap.put(Color.GREEN, "Leaf");
        colorMap.put(Color.BLUE, "Sky");
        System.out.println("Color map: " + colorMap);

        // 3. Retrieving a value
        String blueItem = colorMap.get(Color.BLUE);
        System.out.println("Item associated with BLUE: " + blueItem);

        // 4. Checking if a specific key is present
        boolean hasRed = colorMap.containsKey(Color.RED);
        System.out.println("Map contains RED key: " + hasRed);

        // 5. Checking if a specific value is present
        boolean hasApple = colorMap.containsValue("Apple");
        System.out.println("Map contains 'Apple' value: " + hasApple);

        // 6. Removing a key-value pair
        colorMap.remove(Color.GREEN);
        System.out.println("After removing GREEN key: " + colorMap);

        // 7. Getting the size of the map
        int size = colorMap.size();
        System.out.println("Size of color map: " + size);
    }
}

Output:

Color map: {RED=Apple, GREEN=Leaf, BLUE=Sky}
Item associated with BLUE: Sky
Map contains RED key: true
Map contains 'Apple' value: true
After removing GREEN key: {RED=Apple, BLUE=Sky}
Size of color map: 2

Explanation:

1. Initializing an empty EnumMap that will have Color enum keys.

2. put: Adding key-value pairs to the map using the put method.

3. get: Retrieving the value associated with a specific key.

4. containsKey: Checking if a specific key is present in the map.

5. containsValue: Checking if a specific value is present in the map.

6. remove: Removing a specific key-value pair based on the key.

7. size: Getting the number of key-value pairs present in the map.

EnumMap is a specialized map implementation for use with enumeration type keys. It's compact and efficient, ensuring operations like get or put are faster than their HashMap counterparts when using enum keys.

Real-World Use Case: Tracking Employee Status with EnumMap

import java.util.EnumMap;

// Define an enumeration for employee status
enum Status {
    ONLINE, OFFLINE, ON_LEAVE, IN_MEETING
}

public class EmployeeStatusTracker {
    public static void main(String[] args) {
        // 1. Initializing an EnumMap to track employee status
        EnumMap<Status, String> employeeStatus = new EnumMap<>(Status.class);

        // 2. Assigning employees to their respective statuses
        employeeStatus.put(Status.ONLINE, "Ramesh");
        employeeStatus.put(Status.OFFLINE, "Sunita");
        employeeStatus.put(Status.ON_LEAVE, "Anil");
        employeeStatus.put(Status.IN_MEETING, "Deepa");

        // 3. Displaying the employees based on their status
        for (Status status : Status.values()) {
            System.out.println(status + ": " + employeeStatus.get(status));
        }

        // 4. Changing the status of an employee
        employeeStatus.put(Status.ON_LEAVE, "Ramesh");
        System.out.println("\nAfter updating status:");
        for (Status status : Status.values()) {
            System.out.println(status + ": " + employeeStatus.get(status));
        }
    }
}

Output:

ONLINE: Ramesh
OFFLINE: Sunita
ON_LEAVE: Anil
IN_MEETING: Deepa

After updating status:
ONLINE: null
OFFLINE: Sunita
ON_LEAVE: Ramesh
IN_MEETING: Deepa

Explanation:

1. The Status enum represents different statuses an employee can have.

2. We create an EnumMap named employeeStatus that maps each status to an employee's name. EnumMap is efficient for enums as keys.

3. Initially, employees are assigned to their respective statuses and the map is displayed.

4. Later, Ramesh's status is updated from ONLINE to ON_LEAVE, and the updated map is displayed.

In this use case, EnumMap provides a clear and efficient way to represent and manage the statuses of employees. Enum keys ensure that there's a fixed set of possible statuses, making the system robust against invalid values.

Comments