TreeMap put() method in java

Let’s learn TreeMap put() method in java.

TreeMap put() method in java

put(K key, V value) method of 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.

Syntax:

public V put(K key, V value)

Parameters:

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

value value to be associated with the specified key.

Throws:

ClassCastException – if the specified key cannot be compared with the keys currently in the map.

NullPointerException – if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.

Now let’s see example on TreeMap put() method.

import java.util.TreeMap;
public class TreeMapPutMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(32, "pineapple");
      tm.put(51, "watermelon");
      tm.put(38, "grapes");
      tm.put(69, "mango");
      tm.put(58, "apple");
      // put value at key 3
      System.out.println("TreeMap before using put(K key, V value) method: " + tm);
      System.out.println("Value is: " + tm.put(38, "banana"));
      System.out.println("TreeMap after using put(K key, V value) method: " + tm);
   }
}

Output:

TreeMap before using put(K key, V value) method: {32=pineapple, 38=grapes, 51=watermelon, 58=apple, 69=mango}
Value is: grapes
TreeMap after using put(K key, V value) method: {32=pineapple, 38=banana, 51=watermelon, 58=apple, 69=mango}


Also read – polymorphism in java