java.util.TreeMap.put() Method



The put(K key,V value) method is used to associate 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.


Following is the declaration for java.util.TreeMap.put() method.

public V put(K key,V value)


  • key--This is the key with which the specified value is to be associated.

  • value--This is the value to be associated with the specified key.

Return Value

The method call returns the previous value associated with key, or null if there was no mapping for key.


  • NA


The following example shows the usage of java.util.TreeMap.put()

package com.tutorialspoint;

import java.util.*;

public class TreeMapDemo {
   public static void main(String[] args) {
      // creating tree map 
      TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();
      // populating tree map
      treemap.put(2, "two");
      treemap.put(1, "one");
      treemap.put(3, "three");
      treemap.put(6, "six");
      treemap.put(5, "five");   
      // Putting value at key 3
      System.out.println("Value before modification: "+ treemap);            
      System.out.println("Value returned: "+ treemap.put(3,"TP"));      
      System.out.println("Value after modification: "+ treemap);

Let us compile and run the above program, this will produce the following result.

Value before modification: {1=one, 2=two, 3=three, 5=five, 6=six}
Value returned: three
Value after modification: {1=one, 2=two, 3=TP, 5=five, 6=six}