Java ConcurrentHashMap forEach() Method

The ConcurrentHashMap.forEach() method in Java is used to perform a given action for each entry in the ConcurrentHashMap. This guide will cover the method’s usage, explain how it works, and provide examples to demonstrate its functionality. We will also cover a real-world use case to show how ConcurrentHashMap can be used effectively in a concurrent environment.

Table of Contents

  1. Introduction
  2. forEach Method Syntax
  3. Examples
    • Basic Usage
    • Using BiConsumer
  4. Real-World Use Case
    • Example: Printing Active User Sessions
  5. Conclusion

Introduction

The ConcurrentHashMap.forEach() method is a member of the ConcurrentHashMap class in Java. It allows you to perform a specified action on each entry in the map. The ConcurrentHashMap class is part of the java.util.concurrent package, designed for high concurrency and scalability.

forEach() Method Syntax

The syntax for the forEach method is as follows:

public void forEach(BiConsumer<? super K, ? super V> action)
  • The method takes one parameter:
    • action of type BiConsumer<? super K, ? super V>, which represents the action to be performed for each entry.

Examples

Basic Usage

The forEach method can be used to perform a specified action for each entry in a ConcurrentHashMap.

Example

import java.util.concurrent.ConcurrentHashMap;

public class ForEachExample {
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap with String keys and Integer values
        ConcurrentHashMap<String, Integer> people = new ConcurrentHashMap<>();

        // Adding entries to the ConcurrentHashMap
        people.put("Ravi", 25);
        people.put("Priya", 30);
        people.put("Vijay", 35);

        // Using forEach to print each key-value pair
        people.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

Output:

Ravi: 25
Priya: 30
Vijay: 35

Using BiConsumer

You can use a BiConsumer to perform more complex actions on each entry.

Example

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;

public class BiConsumerExample {
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap with String keys and Integer values
        ConcurrentHashMap<String, Integer> people = new ConcurrentHashMap<>();

        // Adding entries to the ConcurrentHashMap
        people.put("Ravi", 25);
        people.put("Priya", 30);
        people.put("Vijay", 35);

        // Defining a BiConsumer to print a formatted message
        BiConsumer<String, Integer> action = (key, value) -> System.out.println(key + " is " + value + " years old.");

        // Using forEach with the BiConsumer
        people.forEach(action);
    }
}

Output:

Ravi is 25 years old.
Priya is 30 years old.
Vijay is 35 years old.

Real-World Use Case

Example: Printing Active User Sessions

A common real-world use case for ConcurrentHashMap is managing user session data and performing actions on each session entry.

Example

import java.util.concurrent.ConcurrentHashMap;

public class UserSessionStore {
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap to manage user sessions
        ConcurrentHashMap<String, String> userSessions = new ConcurrentHashMap<>();

        // Adding user sessions to the ConcurrentHashMap
        userSessions.put("Ravi", "Active");
        userSessions.put("Priya", "Inactive");
        userSessions.put("Vijay", "Active");

        // Using forEach to print active user sessions
        System.out.println("Active User Sessions:");
        userSessions.forEach((key, value) -> {
            if ("Active".equals(value)) {
                System.out.println(key + ": " + value);
            }
        });
    }
}

Output:

Active User Sessions:
Ravi: Active
Vijay: Active

In this example, ConcurrentHashMap is used to manage user session data, and the forEach method is employed to print active user sessions in a thread-safe manner.

Conclusion

The ConcurrentHashMap.forEach() method in Java provides a way to perform a specified action on each entry in a ConcurrentHashMap in a thread-safe manner. By understanding how to use this method, you can efficiently manage collections of key-value pairs in your Java applications, especially in concurrent environments. The method allows you to perform complex actions on each entry, making it a versatile tool for data management in multi-threaded scenarios.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top