Open In App

How to Merge Two LinkedHashMaps in Java?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, LinkedHashMap is a class that extends HashMap and maintains the order of elements based on the order of insertion. Merging two LinkedHashMaps involves combining their key-value pairs while ensuring that the order is preserved.

In, this article we will explore different approaches to merging two LinkedHashMaps in Java.

Different Approaches to Merge Two LinkedHashMaps in Java

There are two main methods to merge two LinkedHashMaps in Java as mentioned below:

1. Using putAll() method

The simplest way to merge two LinkedHashMaps is by using the putAll() method provided by the Map interface. This method copies all the key-value pairs from one map into another.

Below is the example code for the above approach:

Java




// Java program demonstrating 
// the merging of two LinkedHashMaps
import java.util.LinkedHashMap;
import java.util.Map;
  
public class MergeLinkedHashMaps {
    public static void main(String[] args) {
        // Create the first LinkedHashMap
        LinkedHashMap<String, Integer> map1 = new LinkedHashMap<>();
        map1.put("A", 1);
        map1.put("B", 2);
  
        // Create the second LinkedHashMap
        LinkedHashMap<String, Integer> map2 = new LinkedHashMap<>();
        map2.put("C", 3);
        map2.put("D", 4);
  
        // Merge map2 into map1 using putAll()
        map1.putAll(map2);
  
        // Display the merged LinkedHashMap
        System.out.println("Merged LinkedHashMap: " + map1);
    }
}


Output:

Merged LinkedHashMap: {A=1, B=2, C=3, D=4} 

Explaination of the above program:

  1. Create two LinkedHashMaps: Initialize two instances of LinkedHashMap – map1 and map2.
  2. Insert key-value pairs: Populate both LinkedHashMaps with key-value pairs as needed.
  3. Merge using putAll(): Use the putAll() method on map1 and pass map2 as an argument. This will copy all key-value pairs from map2 into map1.
  4. Result: The LinkedHashMap map1 now contains all key-value pairs from both map1 and map2, with the order preserved.

2. Using Stream API

Another approach is to use the Stream API introduced in Java 8. This method provides more flexibility and can be useful in scenarios where additional processing is required during the merging process.

Below is the example code for the above approach:

Java




// Java program demonstrating the
// merging of two LinkedHashMaps using Stream API
  
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
  
public class MergeLinkedHashMaps {
    public static void main(String[] args) {
        // Create the first LinkedHashMap
        LinkedHashMap<String, Integer> map1 = new LinkedHashMap<>();
        map1.put("A", 1);
        map1.put("B", 2);
  
        // Create the second LinkedHashMap
        LinkedHashMap<String, Integer> map2 = new LinkedHashMap<>();
        map2.put("C", 3);
        map2.put("D", 4);
  
        // Merge the LinkedHashMaps using Stream API
        Map<String, Integer> mergedMap = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,         // Key mapping function
                        Map.Entry::getValue,       // Value mapping function
                        (v1, v2) -> v2,            // Merge function (in case of key collisions, choose the value from the second map)
                        LinkedHashMap::new         // Supplier to create the result map (preserving the order)
                ));
  
        // Display the merged LinkedHashMap
        System.out.println("Merged LinkedHashMap: " + mergedMap);
    }
}


Output:

Merged LinkedHashMap: {A=1, B=2, C=3, D=4}

Explaination of the above program:

  1. Create two LinkedHashMaps: Initialize two instances of LinkedHashMap – map1 and map2.
  2. Insert key-value pairs: Populate both LinkedHashMaps with key-value pairs as needed.
  3. Merge using Stream API:
    • Concatenate Streams: Use Stream.concat() to concatenate the entry sets of both map1 and map2 into a single stream.
    • Collect entries into a new map: Use Collectors.toMap() to collect the entries from the concatenated stream into a new LinkedHashMap.
    • Handle conflicts: If there are key conflicts during merging, resolve them based on your requirements. The example uses the value from the second map.
  4. Result: The new LinkedHashMap contains all key-value pairs from both map1 and map2, with the order preserved.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads