Java TreeMap put(K key, V value) Method Example

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.

Signature

public V put(K key, V value)

This method 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.

Example

The following example shows the usage of java.util.TreeMap.put(key,value) method.

public class PutMethodTreeMapExample 
{
    public static void main(String args[])
    {
        // create an empty TreeMap
        TreeMap<Integer,String>  treeMap1 = new TreeMap<Integer,String>();
        
        // use put() method to put elements to the TreeMap
        treeMap1.put(1,"Element1");
        treeMap1.put(2,"Element2");
        treeMap1.put(3,"Element3");
        treeMap1.put(4,"Element4");
        treeMap1.put(5,"Element5");
        
        //Print the elements of TreeMap before modification
        System.out.println("**Elements of TreeMap before modification**");
        for(Map.Entry<Integer,String> entry : treeMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" ...."+"Value : "+entry.getValue());
        }
        
        //Print the value returned while inserting
        System.out.println("Value returned : "+treeMap1.put(3,"Element333"));
        
        //Print the elements of TreeMap after modification
        System.out.println("**Elements of TreeMap after modification**");
        for(Map.Entry<Integer,String> entry : treeMap1.entrySet())
        {
            System.out.println("Key : "+entry.getKey()+" ...."+"Value : "+entry.getValue());
        }
    }
}

Output

**Elements of TreeMap before modification**
Key : 1 ....Value : Element1
Key : 2 ....Value : Element2
Key : 3 ....Value : Element3
Key : 4 ....Value : Element4
Key : 5 ....Value : Element5
Value returned : Element3
**Elements of TreeMap after modification**
Key : 1 ....Value : Element1
Key : 2 ....Value : Element2
Key : 3 ....Value : Element333
Key : 4 ....Value : Element4
Key : 5 ....Value : Element5

Leave a Reply

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