How to Merge Two TreeMaps in Java?
Last Updated :
25 Jan, 2024
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
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) {
TreeMap<Integer, String> treeMap1 = new TreeMap<>();
TreeMap<Integer, String> treeMap2 = new TreeMap<>();
treeMap1.put( 11 , "Greek" );
treeMap1.put( 12 , "for" );
treeMap1.put( 13 , "Greeks" );
treeMap2.put( 14 , "Merging" );
treeMap2.put( 15 , "two treeMaps" );
treeMap2.put( 16 , "example" );
treeMap1.putAll(treeMap2);
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);
Share your thoughts in the comments
Please Login to comment...