Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
How to Merge Two LinkedHashSet Objects in Java?
Next article icon

How to Merge Two LinkedHashMaps in Java?

Last Updated : 31 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
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.

Next Article
How to Merge Two LinkedHashSet Objects in Java?

V

vishalwaghmode33284
Improve
Article Tags :
  • Java Programs
  • Java Examples

Similar Reads

  • How to Merge Two LinkedHashSet Objects in Java?
    Use the addAll() method to merge two LinkedHashSet objects or append elements of one LinkedHashSet object to another LinkedHashSet object. Comparing with the set, addAll() method is used as Union. The addAll method adds all the elements of the specified collection to this set object. Example: Input
    1 min read
  • How to Convert LinkedHashMap to List in Java?
    LinkedHashMap is predefined class in Java which is similar to HashMap, contains key and its respective value unlike HashMap, in LinkedHashMap insertion order is preserved. We to convert LinkedHashMap to ArrayList. A Map store data in pair of Key and Value while converting a LinkedHashMAp to ArrayLis
    2 min read
  • How to iterate LinkedHashMap in Java?
    LinkedHashMap class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. Th
    2 min read
  • How to Add Key-Value pairs to LinkedHashMap in Java?
    LinkedHashMap is a Hash table and linked list implementation of the Map interface. In LinkedHashMap order of key-value pair depends on the order in which keys were inserted into the map. Insertion order does not affect if a key is reinserted into the map. Example: Input: Key: 1 Value : 1221 Key: 2 V
    2 min read
  • How to Print all Keys of the LinkedHashMap in Java?
    LinkedHashMap is a predefined class in Java that is similar to HashMap, contains a key and its respective value. Unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to print all the Keys present in our LinkedHashMap in java. We have to iterate through each Key in our LinkedHas
    2 min read
  • How to Remove Elements from a LinkedHashMap in Java?
    A LinkedHashMap is a part of the Collection Framework from java.util package Java and is similar to a HashMap, except that a LinkedHashMap preserves the insertion order among the keys/entries. In this article, we will look at how to remove the elements from a LinkedHashMap in Java. Program to Remove
    2 min read
  • How to Print LinkedHashSet Elements in Java?
    LinkedHashSet is a child class of HashSet in which duplicates are not allowed but the insertion order is preserved. The elements are printed in the same order in which they were inserted. There are several ways to print LinkedHashSet elements: By simply printing the elementsBy using enhanced for loo
    5 min read
  • How to Iterate LinkedHashMap in Reverse Order in Java?
    The LinkedHashMap is used to maintain an order of elements inserted into it. It provides where the elements can be accessed in their insertion order. A LinkedHashMap contains values based on the key. It implements the Map interface and extends the HashMap class. It contains only unique elements or m
    6 min read
  • How to Get All the Values of the LinkedHashMap in Java?
    LinkedHashMap is a predefined class in Java that is similar to HashMap, contains key and its respective value, unlike HashMap. In LinkedHashMap insertion order is preserved. The task is to get all the values present in our LinkedHashMap that is linked with their respective key. Use Iteration or pred
    4 min read
  • Java Program to Implement LinkedHashMap API
    The LinkedHashMap is just like HashMap with an additional feature of maintaining an order of elements inserted into it. HashMap provided the advantage of quick insertion, search, and deletion but it never maintained the track and order of insertion which the LinkedHashMap provides where the elements
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences