Java TreeMap - putAll() Method
The java.util.TreeMap.putAll() method is used to copy all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.
Syntax
public void putAll(Map<? extends K,? extends V> m)
Here, K and V are the type of key and value respectively maintained by the container.
Parameters
m |
Specify mappings to be stored in this map. |
Return Value
void type.
Exception
- Throws ClassCastException, if the class of a key or value in the specified map prevents it from being stored in this map.
- Throws NullPointerException, if the specified map is null or the specified map contains a null key and this map does not permit null keys.
Example:
In the example below, the java.util.TreeMap.putAll() method is used to copy all of the mappings from the Map2 to Map1.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating treemaps TreeMap<Integer, String> Map1 = new TreeMap<Integer, String>(); TreeMap<Integer, String> Map2 = new TreeMap<Integer, String>(); //populating Map2 Map2.put(102, "John"); Map2.put(103, "Marry"); Map2.put(101, "Kim"); Map2.put(104, "Jo"); //printing Map1 System.out.println("Before putAll, Map1 contains: " + Map1); //copy mapping from Map2 into Map1 Map1.putAll(Map2); //printing Map1 System.out.println("After putAll, Map1 contains: " + Map1); } }
The output of the above code will be:
Before putAll, Map1 contains: {} After putAll, Map1 contains: {101=Kim, 102=John, 103=Marry, 104=Jo}
❮ Java.util - TreeMap