Java TreeMap putAll(Map map) Method

The put(K key, V value) method of java.util.TreeMap class associates the specified value with the specified key in this map. If the map previously contained a mapping for the key, the old value is replaced whereas putAll(Map<? extends K,? extends V> map) copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of the keys currently in the specified map.

Signature

public void putAll(Map<? extends K,? extends V> map)

This method copies all of the mappings from the specified map to this map. These mappings replace any mappings that this map had for any of the keys currently in the specified map.

Example

The following example shows the usage of java.util.TreeMap.putAll(map) method.

import java.util.Map;
import java.util.TreeMap;

public class PutAllMethodTreeMapExample
{
	public static void main(String args[])
	{
	        // create an empty TreeMap
	        TreeMap<Integer,String> treeMap1 = new TreeMap<Integer,String>();
	        TreeMap<Integer,String> treeMap2 = new TreeMap<Integer,String>();
	        
	        // use put() method to put elements to the TreeMap1
	        treeMap1.put(1,"Element1");
	        treeMap1.put(2,"Element2");
	        treeMap1.put(3,"Element3");
	        treeMap1.put(4,"Element4");
	        treeMap1.put(5,"Element5");
	        
	        System.out.println("**Elements of treeMap1 before putAll()**");
	        
	        //Print the elements of treeMap1
	        for (Map.Entry<Integer,String> entry : treeMap1.entrySet())
	        {
	            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
	        }
	        
	        // use put() method to put elements to the TreeMap2
	        treeMap2.put(10,"Element10");
	        treeMap2.put(11,"Element11");
	        treeMap2.put(12,"Element12");
	        treeMap2.put(13,"Element13");
	        treeMap2.put(14,"Element14");
	        
	        //Put all the elements of treeMap2 to treeMap1
	        treeMap1.putAll(treeMap2);
	        
	        System.out.println("**Elements of treeMap1 after putAll()**");
	        //Print the elements of treeMap1
	        for (Map.Entry<Integer,String> entry : treeMap1.entrySet())
	        {
	            System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
	        }
		}
}

Output

**Elements of treeMap1 before putAll()**
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 3 Value : Element3
Key : 4 Value : Element4
Key : 5 Value : Element5
**Elements of treeMap1 after putAll()**
Key : 1 Value : Element1
Key : 2 Value : Element2
Key : 3 Value : Element3
Key : 4 Value : Element4
Key : 5 Value : Element5
Key : 10 Value : Element10
Key : 11 Value : Element11
Key : 12 Value : Element12
Key : 13 Value : Element13
Key : 14 Value : Element14

Leave a Reply

Your email address will not be published. Required fields are marked *