What is the TreeMap.putAll() method in Java?
In this shot, we will learn how to use the TreeMap.putAll() method in Java.
Introduction
The TreeMap.putAll() method is used to copy all the mappings from one map to another.
The TreeMap.putAll() method is present in the TreeMap class inside the java.util package.
Syntax
The syntax of the TreeMap.putAll() method is given below:
void putAll(Map m);
Parameters
The TreeMap.putAll() accepts one parameter:
Map: The existing map for copying the mappings to another map.
Return value
The TreeMap.putAll() method does not return any value.
Example
Let’s look at the code below.
import java.util.*;class Main{public static void main(String[] args){TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();t1.put(1, "Let's");t1.put(5, "see");t1.put(2, "TreeMap class");t1.put(27, "methods");t1.put(9, "in java.");TreeMap<Integer, String> t2 = new TreeMap<Integer, String>();t2.putAll(t1);System.out.println("The existing treemap is: " + t1);System.out.println("The copy of existing treemap created " +"by putAll() method is: " + t2);}}
Explanation
-
Line 1: We import the required package.
-
Line 2: We create a
Mainclass. -
Line 4: We create a
main()function. -
Line 6: We declare a
TreeMapobjectt1that consists of keys of typeIntegerand values of typeString. -
Lines 8 to 12: We use the
t1.put()method to insert values in theTreeMap. -
Line 14: we declare a new
TreeMapobjectt2that consists of keys of typeIntegerand values of typeString. -
Line 16: We use the
putAll()method to create a copy of the existing mapt1. -
Lines 18 and 19: We display both the existing and new
TreeMapassociated with a message.
So, in this way, we can use the TreeMap.putAll() method in Java.