Java LinkedHashMap merge() Method

The LinkedHashMap.merge() method in Java is used to merge the value associated with a specific key if the key is already present, or insert the value if the key is not present.

Table of Contents

  1. Introduction
  2. merge Method Syntax
  3. Examples
    • Merging Values for Existing Keys
    • Inserting Values for Absent Keys
  4. Real-World Use Case
    • Example: Updating User Scores
  5. Conclusion

Introduction

The LinkedHashMap.merge() method is a member of the LinkedHashMap class in Java. It allows you to merge a value for a specific key if the key is already present in the map, or insert the value if the key is not present. This method is useful for combining values or initializing values when necessary.

merge() Method Syntax

The syntax for the merge method is as follows:

public V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)
  • The method takes three parameters:
    • key of type K, which represents the key whose value is to be merged.
    • value of type V, which represents the value to be merged.
    • remappingFunction of type BiFunction<? super V, ? super V, ? extends V>, which represents the function to compute a value.
  • The method returns the new value associated with the specified key, or null if the computed value is null.

Examples

Merging Values for Existing Keys

The merge method can be used to combine values for keys that are already present in the LinkedHashMap.

Example

import java.util.LinkedHashMap;
import java.util.function.BiFunction;

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

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

        // Merging a value for an existing key
        Integer newAge = people.merge("Priya", 5, new BiFunction<Integer, Integer, Integer>() {
            @Override
            public Integer apply(Integer oldValue, Integer newValue) {
                return oldValue + newValue;
            }
        });

        // Printing the result and the LinkedHashMap after merging
        System.out.println("New age for Priya: " + newAge);
        System.out.println("LinkedHashMap after merging: " + people);
    }
}

Output:

New age for Priya: 35
LinkedHashMap after merging: {Ravi=25, Priya=35}

Using Lambda Expression with merge

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

Example

import java.util.LinkedHashMap;

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

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

        // Merging a value for an existing key using a lambda expression
        Integer newAge = people.merge("Priya", 5, (oldValue, newValue) -> oldValue + newValue);

        // Printing the result and the LinkedHashMap after merging
        System.out.println("New age for Priya: " + newAge);
        System.out.println("LinkedHashMap after merging: " + people);
    }
}

Output:

New age for Priya: 35
LinkedHashMap after merging: {Ravi=25, Priya=35}

Inserting Values for Absent Keys

The merge method inserts the value if the key is not already present in the LinkedHashMap.

Example

import java.util.LinkedHashMap;

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

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

        // Merging a value for a key that is absent
        Integer newAge = people.merge("Vijay", 35, (oldValue, newValue) -> oldValue + newValue);

        // Printing the result and the LinkedHashMap after merging
        System.out.println("New age for Vijay: " + newAge);
        System.out.println("LinkedHashMap after merging: " + people);
    }
}

Output:

New age for Vijay: 35
LinkedHashMap after merging: {Ravi=25, Priya=30, Vijay=35}

Real-World Use Case

Example: Updating User Scores

A common real-world use case for LinkedHashMap.merge() is updating user scores in a game. For example, let's consider a scenario where user scores are stored in a LinkedHashMap, and we need to update the scores by adding new points.

Example

import java.util.LinkedHashMap;

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

        // Adding some user scores to the LinkedHashMap
        userScores.put("Ravi", 100);
        userScores.put("Priya", 150);

        // Updating scores using merge
        userScores.merge("Ravi", 50, (oldScore, newScore) -> oldScore + newScore);
        userScores.merge("Vijay", 200, (oldScore, newScore) -> oldScore + newScore);

        // Printing the updated user scores
        System.out.println("Updated User Scores: " + userScores);
    }
}

Output:

Updated User Scores: {Ravi=150, Priya=150, Vijay=200}

In this example, LinkedHashMap.merge() is used to update user scores by adding new points, demonstrating how to handle both existing and absent keys effectively.

Conclusion

The LinkedHashMap.merge() method in Java provides a way to merge values for specific keys if they are already present, or insert values if the keys are not present. By understanding how to use this method, you can efficiently manage and combine values in your Java applications, making it a versatile tool for data management.

Comments