TreeMap higherEntry(K) in Java

higherEntry(K): This method is available in java.util.TreeMap class of Java.

Syntax:

Entry<K, V> java.util.TreeMap.higherEntry(K key)

This method takes one argument. This method returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key.

Parameters: One parameter is required for this method.

key: the key.

Returns: an entry with the least key greater than the key, or null if there is no such 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 TreeMaphigherEntry {
    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");

        Integer key = 11;

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

    }
}

Output:

23=Program


Approach 2: NullPointerException 

Java

import java.util.TreeMap;

public class TreeMaphigherEntry {
    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");

        Integer key = null;

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

    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Comparable.compareTo(Object)" because "k1" is null at java.base/java.util.TreeMap.compare(TreeMap.java:1563) at java.base/java.util.TreeMap.getHigherEntry(TreeMap.java:461) at java.base/java.util.TreeMap.higherEntry(TreeMap.java:1035)


No comments:

Post a Comment