Java LinkedHashMap forEach() Method

The LinkedHashMap.forEach(BiConsumer<? super K, ? super V> action) method in Java is used to perform the given action for each entry in the LinkedHashMap.

Table of Contents

  1. Introduction
  2. forEach Method Syntax
  3. Examples
    • Iterating Over Entries in a LinkedHashMap
    • Modifying Entries Using forEach
  4. Real-World Use Case
    • Example: Displaying User Information
  5. Conclusion

Introduction

The LinkedHashMap.forEach(BiConsumer<? super K, ? super V> action) method is a member of the LinkedHashMap class in Java. It allows you to perform a specified action for each entry in the map. The action is specified as a BiConsumer that takes two arguments: the key and the value. This method is useful for applying operations to all entries in the map.

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.
  • The method does not return a value.

Examples

Iterating Over Entries in a LinkedHashMap

The forEach method can be used to iterate over the entries in a LinkedHashMap.

Example

import java.util.LinkedHashMap;
import java.util.function.BiConsumer;

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

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

        // Using forEach to iterate over the entries
        people.forEach(new BiConsumer<String, Integer>() {
            @Override
            public void accept(String key, Integer value) {
                System.out.println(key + ": " + value);
            }
        });
    }
}

Output:

Ravi: 25
Priya: 30
Vijay: 35

Using Lambda Expression with forEach

You can also use a lambda expression to simplify the code.

Example

import java.util.LinkedHashMap;

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

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

        // Using forEach with a lambda expression to iterate over the entries
        people.forEach((key, value) -> System.out.println(key + ": " + value));
    }
}

Output:

Ravi: 25
Priya: 30
Vijay: 35

Modifying Entries Using forEach

You can also modify the values in the LinkedHashMap using the forEach method.

Example

import java.util.LinkedHashMap;

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

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

        // Using forEach to modify the values
        people.forEach((key, value) -> {
            if (key.equals("Priya")) {
                people.put(key, value + 1);
            }
        });

        // Printing the modified LinkedHashMap
        System.out.println("Modified LinkedHashMap: " + people);
    }
}

Output:

Modified LinkedHashMap: {Ravi=25, Priya=31, Vijay=35}

Real-World Use Case

Example: Displaying User Information

A common real-world use case for LinkedHashMap.forEach(BiConsumer<? super K, ? super V> action) is displaying user information stored in a LinkedHashMap. For example, let's consider a scenario where user profiles are stored with usernames as keys and ages as values.

Example

import java.util.LinkedHashMap;

public class DisplayUserInformation {
    public static void main(String[] args) {
        // Creating a LinkedHashMap to store user profiles
        LinkedHashMap<String, Integer> userProfiles = new LinkedHashMap<>();

        // Adding user profiles to the LinkedHashMap
        userProfiles.put("Ravi", 25);
        userProfiles.put("Priya", 30);
        userProfiles.put("Vijay", 35);

        // Using forEach to display user information
        System.out.println("User Information:");
        userProfiles.forEach((username, age) -> System.out.println("Username: " + username + ", Age: " + age));
    }
}

Output:

User Information:
Username: Ravi, Age: 25
Username: Priya, Age: 30
Username: Vijay, Age: 35

In this example, LinkedHashMap.forEach(BiConsumer<? super K, ? super V> action) is used to display user information stored in a LinkedHashMap, demonstrating how to iterate over and access entries in the map.

Conclusion

The LinkedHashMap.forEach() method in Java provides a way to perform a specified action for each entry in the LinkedHashMap. By understanding how to use this method, you can efficiently manage and manipulate collections of key-value pairs in your Java applications. The method allows you to iterate over entries, modify values, and perform operations based on the entries, making it a versatile tool for data management.

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments