Java Utility Library

Java TreeMap - put() Method



The java.util.TreeMap.put() method is used to associate the specified value with the specified key in the map. If the key is already present in the map, the old value is replaced.

Syntax

public V put(K key, V value)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

key Specify the key with which the specified value is to be associated.
value Specify the value to be associated with the specified key.

Return Value

Returns previous value associated with given key, or null if there was no mapping for key.

Exception

  • Throws ClassCastException, if the specified key cannot be compared with the keys currently in the map.
  • Throws NullPointerException, if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.

Example:

In the example below, the java.util.TreeMap.put() method is used to associate key-value pairs in the given map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treemap
    TreeMap<Integer, String> MyMap = new TreeMap<Integer, String>();

    //populating the map
    MyMap.put(102, "John");
    MyMap.put(103, "Marry");
    MyMap.put(101, "Kim");
    MyMap.put(104, "Jo");

    //printing the map
    System.out.println("MyMap contains: " + MyMap);    

    //change a key-value pair
    MyMap.put(103, "Ramesh"); 

    //printing the map
    System.out.println("MyMap contains: " + MyMap);  
  }
}

The output of the above code will be:

MyMap contains: {101=Kim, 102=John, 103=Marry, 104=Jo}
MyMap contains: {101=Kim, 102=John, 103=Ramesh, 104=Jo}

❮ Java.util - TreeMap