This Java code defines a class named Copy_TreeMap which contains a main method that creates two TreeMap objects named s1 and s2 and adds key-value pairs to them. The keys are integers and the values are strings representing the names of individuals. The keys are inserted in ascending order from 10 to 50 for s1 and from 60 to 80 for s2.
The code then prints the contents of both TreeMap objects to the console. Next, the putAll() method of the TreeMap class is used to copy all the key-value pairs from s2 to s1. This method merges the contents of the two maps, with the values in s2 overwriting the values in s1 for any keys that are present in both maps.
Finally, the code prints the contents of s1 to the console again to show the updated key-value pairs. This code demonstrates how to copy the contents of one TreeMap into another using the putAll() method, which is a convenient way to merge the contents of two maps.
import java.util.*; public class Copy_TreeMap { public static void main(String args[]) { TreeMap<Integer,String> s1 = new TreeMap<Integer,String>(); s1.put(10, "John"); s1.put(20, "Joes"); s1.put(30, "Smith"); s1.put(40, "Charles"); s1.put(50, "George"); System.out.println("TreeMap 1 : "+s1); TreeMap<Integer,String> s2 = new TreeMap<Integer,String>(); s2.put(60, "Kevin"); s2.put(70, "Aryan"); s2.put(80, "Dhruv"); System.out.println("TreeMap 2 : "+s2); s1.putAll(s2); System.out.println("After Coping TreeMap2 to TreeMap1 : "); for (Map.Entry<Integer,String> entry : s1.entrySet()) { System.out.println(entry.getKey() + " , " + entry.getValue()); } } }
TreeMap 1 : {10=John, 20=Joes, 30=Smith, 40=Charles, 50=George} TreeMap 2 : {60=Kevin, 70=Aryan, 80=Dhruv} After Coping TreeMap2 to TreeMap1 : 10 , John 20 , Joes 30 , Smith 40 , Charles 50 , George 60 , Kevin 70 , Aryan 80 , Dhruv
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions