Java EnumMap getOrDefault() Method

The EnumMap.getOrDefault(Object key, V defaultValue) method in Java is used to return the value associated with the specified key, or a default value if the key is not present in the map. This guide will cover the method's usage with examples, and we will also cover a real-world use case to show how EnumMap.getOrDefault() can be used effectively.

Table of Contents

  1. Introduction
  2. getOrDefault Method Syntax
  3. Examples
    • Basic Usage of getOrDefault Method
    • Handling Non-Existent Keys with Default Values
  4. Real-World Use Case
    • Example: Retrieving Default Task for Unassigned Days
  5. Conclusion

Introduction

The EnumMap.getOrDefault(Object key, V defaultValue) method is a member of the EnumMap class in Java. It allows you to retrieve the value associated with the specified key, or return a default value if the key is not present in the map.

getOrDefault() Method Syntax

The syntax for the getOrDefault method is as follows:

public V getOrDefault(Object key, V defaultValue)
  • Parameters:
    • key: The key whose associated value is to be returned.
    • defaultValue: The value to be returned if the key is not found in the map.
  • Returns: The value associated with the specified key, or defaultValue if the key is not found.

Examples

Basic Usage of getOrDefault Method

The getOrDefault method can be used to retrieve a value associated with a key or a default value if the key is not present in the EnumMap.

Example

import java.util.EnumMap;

public class EnumMapGetOrDefaultExample {
    // Define an enum representing days of the week
    enum Day {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }

    public static void main(String[] args) {
        // Create an EnumMap with Day as key and String as value
        EnumMap<Day, String> tasks = new EnumMap<>(Day.class);

        // Adding entries to the EnumMap
        tasks.put(Day.MONDAY, "Go to gym");
        tasks.put(Day.TUESDAY, "Attend meeting");

        // Using getOrDefault to retrieve a value or a default value
        String taskMonday = tasks.getOrDefault(Day.MONDAY, "No task assigned");
        String taskSunday = tasks.getOrDefault(Day.SUNDAY, "No task assigned");

        // Printing the results
        System.out.println("Task for Monday: " + taskMonday);
        System.out.println("Task for Sunday: " + taskSunday);
    }
}

Output:

Task for Monday: Go to gym
Task for Sunday: No task assigned

Handling Non-Existent Keys with Default Values

You can use the getOrDefault method to handle cases where a key is not present in the EnumMap, providing a default value instead.

Example

import java.util.EnumMap;

public class EnumMapDefaultExample {
    // Define an enum representing months of the year
    enum Month {
        JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
    }

    public static void main(String[] args) {
        // Create an EnumMap with Month as key and String as value
        EnumMap<Month, String> holidays = new EnumMap<>(Month.class);

        // Adding entries to the EnumMap
        holidays.put(Month.JANUARY, "New Year's Day");
        holidays.put(Month.DECEMBER, "Christmas Day");

        // Using getOrDefault to handle non-existent keys
        String holidayMarch = holidays.getOrDefault(Month.MARCH, "No holiday");
        String holidayDecember = holidays.getOrDefault(Month.DECEMBER, "No holiday");

        // Printing the results
        System.out.println("Holiday in March: " + holidayMarch);
        System.out.println("Holiday in December: " + holidayDecember);
    }
}

Output:

Holiday in March: No holiday
Holiday in December: Christmas Day

Real-World Use Case

Example: Retrieving Default Task for Unassigned Days

A common real-world use case for EnumMap.getOrDefault() is retrieving default tasks for days where no specific task has been assigned.

Example

import java.util.EnumMap;

public class TaskAssigner {
    // Define an enum representing days of the week
    enum Day {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
    }

    public static void main(String[] args) {
        // Create an EnumMap to manage tasks for each day
        EnumMap<Day, String> tasks = new EnumMap<>(Day.class);

        // Adding tasks for specific days
        tasks.put(Day.MONDAY, "Go to gym");
        tasks.put(Day.TUESDAY, "Attend meeting");
        tasks.put(Day.FRIDAY, "Project presentation");

        // Using getOrDefault to retrieve tasks for all days, with a default task
        for (Day day : Day.values()) {
            String task = tasks.getOrDefault(day, "No specific task assigned");
            System.out.println("Task for " + day + ": " + task);
        }
    }
}

Output:

Task for MONDAY: Go to gym
Task for TUESDAY: Attend meeting
Task for WEDNESDAY: No specific task assigned
Task for THURSDAY: No specific task assigned
Task for FRIDAY: Project presentation
Task for SATURDAY: No specific task assigned
Task for SUNDAY: No specific task assigned

In this example, EnumMap.getOrDefault() is used to retrieve tasks for all days of the week, providing a default task for days that do not have specific tasks assigned.

Conclusion

The EnumMap.getOrDefault(Object key, V defaultValue) method in Java provides a way to retrieve the value associated with a specified key or return a default value if the key is not found. By understanding how to use this method, you can efficiently handle cases where keys may not be present in the map and provide meaningful default values. This method allows you to manage and utilize the entries in an EnumMap, making it a versatile tool for managing data in various scenarios.

Comments