How to Copy Key-Value Pairs from One TreeMap to Another in Java?
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:
Java
// Java program to copy key-value pairs from one TreeMap to another using putAll() import java.util.TreeMap; public class CopyTreeMap { public static void main(String[] args) { // Create the course TreeMap TreeMap<String, Integer> courseTreeMap = new TreeMap<>(); courseTreeMap.put( "Core Java" , 10000 ); courseTreeMap.put( "Spring Boot" , 20000 ); courseTreeMap.put( "AWS" , 25000 ); // Print the course TreeMap System.out.println( "Course TreeMap: " + courseTreeMap); // Create the another TreeMap TreeMap<String, Integer> newCourseTreeMap = new TreeMap<>(); // Copy key-value pairs using putAll() method newCourseTreeMap.putAll(courseTreeMap); // Print the newCourse TreeMap System.out.println( "New Course TreeMap: " + newCourseTreeMap); } } |
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
Contact Us