Java EnumMap forEach() Method

The EnumMap.forEach(BiConsumer<? super K, ? super V> action) method in Java is used to perform the given action for each entry 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.forEach() can be used effectively.

Table of Contents

  1. Introduction
  2. forEach Method Syntax
  3. Examples
    • Basic Usage of forEach Method
    • Applying Actions to Entries
  4. Real-World Use Case
    • Example: Printing Task Assignments with Details
  5. Conclusion

Introduction

The EnumMap.forEach() method is a member of the EnumMap class in Java. It allows you to perform a specified action for each key-value pair in the map. The action is defined by a BiConsumer functional interface that accepts two input arguments and performs an operation on them.

forEach() Method Syntax

The syntax for the forEach method is as follows:

public void forEach(BiConsumer<? super K, ? super V> action)
  • Parameters:
    • action: The action to be performed for each entry in the map.
  • Returns: This method does not return a value.

Examples

Basic Usage of forEach Method

The forEach method can be used to apply a specified action to each key-value pair in an EnumMap.

Example

import java.util.EnumMap;
import java.util.function.BiConsumer;

public class EnumMapForEachExample {
    // 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");
        tasks.put(Day.WEDNESDAY, "Work from home");

        // Using forEach to print all entries
        tasks.forEach((day, task) -> System.out.println(day + ": " + task));
    }
}

Output:

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

Applying Actions to Entries

You can use the forEach method to apply complex actions to each entry in an EnumMap.

Example

import java.util.EnumMap;
import java.util.function.BiConsumer;

public class EnumMapForEachActionExample {
    // Define an enum representing types of fruits
    enum Fruit {
        APPLE, BANANA, ORANGE, MANGO, GRAPE
    }

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

        // Adding entries to the EnumMap
        fruitMap.put(Fruit.APPLE, 10);
        fruitMap.put(Fruit.BANANA, 20);
        fruitMap.put(Fruit.ORANGE, 30);

        // Using forEach to perform a complex action on each entry
        fruitMap.forEach((fruit, quantity) -> {
            int newQuantity = quantity + 5; // Increment each quantity by 5
            System.out.println("Updated quantity of " + fruit + ": " + newQuantity);
        });
    }
}

Output:

Updated quantity of APPLE: 15
Updated quantity of BANANA: 25
Updated quantity of ORANGE: 35

Real-World Use Case

Example: Printing Task Assignments with Details

A common real-world use case for EnumMap.forEach() is printing out all task assignments for the week with additional details.

Example

import java.util.EnumMap;
import java.util.function.BiConsumer;

public class DetailedTaskPrinter {
    // 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 each day
        tasks.put(Day.MONDAY, "Go to gym");
        tasks.put(Day.TUESDAY, "Attend meeting");
        tasks.put(Day.WEDNESDAY, "Work from home");
        tasks.put(Day.THURSDAY, "Team lunch");
        tasks.put(Day.FRIDAY, "Project presentation");
        tasks.put(Day.SATURDAY, "Family time");
        tasks.put(Day.SUNDAY, "Rest day");

        // Using forEach to print all task assignments with additional details
        tasks.forEach((day, task) -> {
            System.out.println("On " + day + ", you need to: " + task);
        });
    }
}

Output:

On MONDAY, you need to: Go to gym
On TUESDAY, you need to: Attend meeting
On WEDNESDAY, you need to: Work from home
On THURSDAY, you need to: Team lunch
On FRIDAY, you need to: Project presentation
On SATURDAY, you need to: Family time
On SUNDAY, you need to: Rest day

In this example, EnumMap.forEach() is used to print out all task assignments for the week with additional details, making it easy to see the schedule.

Conclusion

The EnumMap.forEach(BiConsumer<? super K, ? super V> action) method in Java provides a way to perform a specified action for each key-value pair in the map. By understanding how to use this method, you can efficiently apply operations to all entries 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