TreeMap putAll() Method in Java
The putAll()
method in Java TreeMap is used to copy all the key-value pairs from one TreeMap to another. It takes a single argument, which is the TreeMap from which the key-value pairs are to be copied.
Syntax:
public void putAll(Map<? extends K,? extends V> map)
Parameters:
- map
: The TreeMap from which the key-value pairs are to be copied.
Return Value: This method does not return any value.
Example:
// Creating a TreeMap
TreeMap<Integer, String> treeMap1 = new TreeMap<>();
treeMap1.put(1, "One");
treeMap1.put(2, "Two");
treeMap1.put(3, "Three");
// Creating another TreeMap
TreeMap<Integer, String> treeMap2 = new TreeMap<>();
// Copying all the key-value pairs from treeMap1 to treeMap2
treeMap2.putAll(treeMap1);
// Displaying the key-value pairs of treeMap2
System.out.println("treeMap2: " + treeMap2);
Output:
treeMap2: {1=One, 2=Two, 3=Three}
In the above example, we have created two TreeMaps treeMap1
and treeMap2
. We have added some key-value pairs to treeMap1
. Then, we have used the putAll()
method to copy all the key-value pairs from treeMap1
to treeMap2
. Finally, we have displayed the key-value pairs of treeMap2
.