TreeMap remove(Object key) method in java

Let’s learn TreeMap remove(Object key) method in java.

TreeMap remove(Object key) method in java

remove(Object key) method of TreeMap class removes the mapping for this key from this TreeMap if present.


public V remove(Object key)


key key for which mapping should be removed.


the previous value associated with key, or null if there was no mapping for key.(A null return can also indicate that the map previously associated null with key.)


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 remove(Object key) method.

import java.util.TreeMap;
public class TreeMapRemoveMethodExample
   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");
      System.out.println("Given TreeMap is: " + tm);
      // remove existing key mapping
      String strReturn = (String)tm.remove(38);
      System.out.println("Returned value is: " + strReturn);
      System.out.println("New TreeMap is: " + tm);


Given TreeMap is: {32=pineapple, 38=grapes, 51=watermelon, 58=apple, 69=mango}
Returned value is: grapes
New TreeMap is: {32=pineapple, 51=watermelon, 58=apple, 69=mango}

Also read – interface in java