What is the TreeMap.remove() method in Java?
In this shot, we will learn how to use the TreeMap.remove() method, which is present in the TreeMap class inside the java.util package.
The TreeMap.remove() method is used to remove the key-value mapping of the specified key.
Syntax
The syntax of the TreeMap.remove() method is given below:
V remove(K key);
Parameter
TreeMap.remove() accepts one parameter:
Key: The key whose mapping is to be removed from the map.
Return
The TreeMap.remove() method can return either of the two values mentioned below:
Value: The value associated with the specified key previously in the map.Null: If the key doesn’t exist.
Code
Let’s have a look at the code.
import java.util.TreeMap;class Main{public static void main(String[] args){TreeMap<Integer, String> t1 = new TreeMap<Integer, String>();t1.put(1, "Let's");t1.put(5, "see");t1.put(2, "TreeMap class");t1.put(27, "methods");t1.put(9, "in java.");System.out.println("The existing treemap is: " + t1);System.out.println("Value removed is: " + t1.remove(27));System.out.println("Value removed is: " + t1.remove(77));System.out.println("The treemap after removing key=27 is: " + t1);}}
Explanation
-
Line 1: We import the required package.
-
Line 2: We make the
Mainclass. -
Line 4: We make a
main()function. -
Line 6: We declare a
TreeMapconsisting ofIntegertype keys andStringtype values. -
Lines 8 to 12: We insert values in the
TreeMapby using theTreeMap.put()method. -
Line 14: We display the original
TreeMap. -
Line 16: We use the
remove()method to remove a key-value mapping of the specified key. -
Line 18: We again use the
remove()method to remove a key-value mapping of the specified key which is not present in theTreeMap. -
Line 20: We display the modified
TreeMapwith the removed key-value mapping of the specified key associated with a message.
So, this is how to use the TreeMap.remove() method in Java.