TreeMap remove(Object, Object) in Java

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

Syntax:

boolean java.util.Map.remove(Object key, Object value)

This method takes two arguments. This method removes the entry for the specified key only if it is currently mapped to the specified value.

Parameters: Two parameters are required for this method.

key: key with which the specified value is associated.

value: value expected to be associated with the specified key.

Returns: true if the value was removed.

Throws:

1. UnsupportedOperationException - if the remove operation is not supported by this map.

2. ClassCastException - if the key or value is of an in appropriate type for this map.

3. NullPointerException - if the specified key or value is null,and this map does not permit null keys or values.

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMapremove2 {
    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;

        Object value = "Java";

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

    }
}

Output:

true


Approach 2: NullPointerException

Java

import java.util.TreeMap;

public class TreeMapremove2 {
    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;

        Object value = "Java";

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

    }
}

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.get(TreeMap.java:279) at java.base/java.util.Map.remove(Map.java:815)


No comments:

Post a Comment