VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-copy-key-value-pairs-from-one-treemap-to-another-in-java/

⇱ How to Copy Key-Value Pairs from One TreeMap to Another in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Copy Key-Value Pairs from One TreeMap to Another in Java?

Last Updated : 23 Jul, 2025

In Java, a TreeMap is a Map implementation that stores key-value pairs in a red-black tree structure. It allows insertions and deletions of key-value pairs due to its tree implementation. These operations take O(log n) time on average.

In this article, we will be learning how to copy key-value pairs from one TreeMap to another in Java.

Syntax:

newTreeMap.putAll(originalTreeMap);

This will copy all the key-value pairs from originalTreeMap to newTreeMap.

Program to Copy Key-Value Pairs from One TreeMap to Another in Java

To copy key-value pairs from one TreeMap to another, we can use putAll() method. Below is the code implementation for this:


Output
Course TreeMap: {AWS=25000, Core Java=10000, Spring Boot=20000}
New Course TreeMap: {AWS=25000, Core Java=10000, Spring Boot=20000}

Explanation of the above Program:

  • In the above program, it creates an original TreeMap with course names and fees as keys and values.
  • A new empty TreeMap is created to copy the data to.
  • We have used the putAll() method to copy all key-value pairs from the original map to the new map.
  • This copies the entire contents of one map to another map in one line.
  • Printing both maps verifies the data is successfully copied from one to the other.

Note: putAll() method to easily copy all elements from one TreeMap to another in a single line of code

Comment