Java EnumMap putIfAbsent() Method

The EnumMap.putIfAbsent(K key, V value) method in Java is used to associate the specified value with the specified key if the key is not already associated with a value. This guide will cover the method's usage with examples, and we will also cover a real-world use case to show how EnumMap.putIfAbsent() can be used effectively.

Table of Contents

  1. Introduction
  2. putIfAbsent Method Syntax
  3. Examples
    • Basic Usage of putIfAbsent Method
    • Handling Existing Keys
  4. Real-World Use Case
    • Example: Assigning Default Tasks to Unassigned Days
  5. Conclusion

Introduction

The EnumMap.putIfAbsent(K key, V value) method is a member of the EnumMap class in Java. It allows you to associate a specified value with a specified key if the key is not already associated with a value. If the key is already associated with a value, the method returns the current value without making any changes.

putIfAbsent() Method Syntax

The syntax for the putIfAbsent method is as follows:

public V putIfAbsent(K key, V value)
  • Parameters:
    • key: The key with which the specified value is to be associated.
    • value: The value to be associated with the specified key.
  • Returns: The current value associated with the specified key, or null if there was no mapping for the key.

Examples

Basic Usage of putIfAbsent Method

The putIfAbsent method can be used to add a key-value pair to an EnumMap only if the key is not already present.

Example

import java.util.EnumMap;

public class EnumMapPutIfAbsentExample {
    // 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 putIfAbsent to add a value only if the key is not present
        tasks.putIfAbsent(Day.MONDAY, "Read a book");
        tasks.putIfAbsent(Day.WEDNESDAY, "Work from home");

        // Printing the EnumMap
        tasks.forEach((day, task) -> System.out.println(day + ": " + task));
    }
}

Output:

MONDAY: Go to gym
TUESDAY: Attend meeting
WEDNESDAY: Work from home

Handling Existing Keys

If the key is already associated with a value, the putIfAbsent method returns the current value and does not make any changes.

Example

import java.util.EnumMap;

public class EnumMapExistingKeyExample {
    // 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 putIfAbsent to add a value only if the key is not present
        String januaryHoliday = holidays.putIfAbsent(Month.JANUARY, "Republic Day");
        String marchHoliday = holidays.putIfAbsent(Month.MARCH, "Holi");

        // Printing the results
        System.out.println("Holiday in January (existing): " + januaryHoliday);
        System.out.println("Holiday in March (new): " + marchHoliday);

        // Printing the EnumMap
        holidays.forEach((month, holiday) -> System.out.println(month + ": " + holiday));
    }
}

Output:

Holiday in January (existing): New Year's Day
Holiday in March (new): null
JANUARY: New Year's Day
DECEMBER: Christmas Day
MARCH: Holi

Real-World Use Case

Example: Assigning Default Tasks to Unassigned Days

A common real-world use case for EnumMap.putIfAbsent() is assigning default tasks to days that do not already have specific tasks 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 putIfAbsent to assign default tasks for unassigned days
        for (Day day : Day.values()) {
            tasks.putIfAbsent(day, "No specific task assigned");
        }

        // Printing the tasks for each day
        tasks.forEach((day, task) -> 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.putIfAbsent() is used to assign default tasks for days that do not have specific tasks assigned, ensuring that every day has a task associated with it.

Conclusion

The EnumMap.putIfAbsent(K key, V value) method in Java provides a way to associate a specified value with a specified key only if the key is not already associated with a value. By understanding how to use this method, you can efficiently manage default values and prevent overwriting existing values in collections where the keys are enum constants. 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