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.
The syntax of the TreeMap.remove()
method is given below:
V remove(K key);
TreeMap.remove()
accepts one parameter:
Key
: The key whose mapping is to be removed from the map.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.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);}}
Line 1: We import the required package.
Line 2: We make the Main
class.
Line 4: We make a main()
function.
Line 6: We declare a TreeMap
consisting of Integer
type keys and String
type values.
Lines 8 to 12: We insert values in the TreeMap
by using the TreeMap.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 the TreeMap
.
Line 20: We display the modified TreeMap
with 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.