VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-merge-two-treemaps-in-java/

⇱ How to Merge Two TreeMaps in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Merge Two TreeMaps in Java?

Last Updated : 23 Jul, 2025

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:


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