Open In App

How to Merge Two TreeMaps in Java?

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

In Java, TreeMap is a pre-defined class that implements the NavigableMap interface and extends the AbstractMap class. In this article, we will learn to Merge Two Tree Maps in Java.

Program to Merge Two TreeMaps in Java

We are using the putAll method is inherited from the AbstractMap class in this manner possible. All mappings between TreeMaps are replicated using this technique.

  • put: Accept the two parameters are key and value
  • putAll: Accept the one parameter as a TreeMap object

Below is the implementation to Merge Two TreeMaps in Java:

Java




// Java code to show the implementation of 
// putAll method in TreeMap class
import java.io.*;
import java.util.*;
  
// Driver Class
class GFG {
      // Main Function
    public static void main (String[] args) {
        
      // Creating the two treeMaps
      TreeMap<Integer, String> treeMap1 = new TreeMap<>();
      TreeMap<Integer, String> treeMap2 = new TreeMap<>();
        
      // Adding the values into the treeMap1
      treeMap1.put(11,"Greek");
      treeMap1.put(12,"for");
      treeMap1.put(13,"Greeks");
        
      // Adding the values into the treeMap2
      treeMap2.put(14,"Merging");
      treeMap2.put(15,"two treeMaps");
      treeMap2.put(16,"example");
        
      // Merge the TreeMaps using putAll
      treeMap1.putAll(treeMap2);
        
      // Print the Merged TreeMap
      System.out.println("Merged TreeMap:"+treeMap1);
    }
}


Output

Merged TreeMap:{11=Greek, 12=for, 13=Greeks, 14=Merging, 15=two treeMaps, 16=example}


Explaination of the above Program:

Inserting Elements in First TreeMap and then in another TreeMap. After that we can use putAll() to put all the elements in the TreeMap1 after using the statement mentioned below:

TreeMap1.putAll(TreeMap2);

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads