TreeMap get(Object) in Java

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

Syntax:

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

This method takes one argument. This method returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

Parameters: One parameter is required for this method.

key: the key whose associated value is to be returned.

Returns: the value to which the specified key is mapped, or null if this map contains no mapping for the 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 TreeMapget {
    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 = 10;
        System.out.println(treeMap.get(key));

    }
}

Output:

null


Approach 2: NullPointerException

Java

import java.util.TreeMap;

public class TreeMapget {
    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.get(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.get(TreeMap.java:279)


No comments:

Post a Comment