Java TreeMap - remove() Method
The java.util.TreeMap.remove() method is used to remove the mapping for the specified key from this map if present.
Syntax
public V remove(Object key)
Here, V is the type of value maintained by the container.
Parameters
key |
Specify key whose mapping is to be removed. |
Return Value
Returns 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.)
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.remove() method is used to remove the mapping for the specified key from 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(101, "John"); MyMap.put(102, "Marry"); MyMap.put(103, "Kim"); MyMap.put(104, "Jo"); //printing the map System.out.println("Before remove, MyMap contains: " + MyMap); //remove mapping for 102 key MyMap.remove(102); //printing the map System.out.println("After remove, MyMap contains: " + MyMap); } }
The output of the above code will be:
Before remove, MyMap contains: {101=John, 102=Marry, 103=Kim, 104=Jo} After remove, MyMap contains: {101=John, 103=Kim, 104=Jo}
❮ Java.util - TreeMap