TreeMap remove(Object) in Java

remove(Object): This method is available in java.util.TreeMap class of Java.

Syntax:

String java.util.TreeMap.remove(Object key)

This method takes one argument. This method removes the mapping for this key from this TreeMap if present.

Parameters: One parameter is required for this method.

key: key for which mapping should be removed.

Returns: the previous value associated with key, or null if there was no mapping for key.

Throws:

1. ClassCastException - if the specified key cannot be compared with the keys currently on the map.

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

Approach 1: When no exception

Java 

import java.util.TreeMap;

public class TreeMapremove {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Object key = 11;

        System.out.println(treeMap.remove(key));

    }
}

Output:

Java


Approach 2: NullPointerException

Java

import java.util.TreeMap;

public class TreeMapremove {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Object key = null;

        System.out.println(treeMap.remove(key));

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.TreeMap.getEntry(TreeMap.java:345) at java.base/java.util.TreeMap.remove(TreeMap.java:873)


No comments:

Post a Comment