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 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);
}
} |
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);