Java EnumMap Real-Time Example

In this source code example, you will learn how to use the EnumMap class in real-time Java projects.

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.

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