TreeMap tailMap(K) in Java

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

Syntax:

SortedMap<K, V> java.util.TreeMap.tailMap(K fromKey)

This method takes one argument. This method returns a view of the portion of this map whose keys are greater than or equal to fromKey.

Note: The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa.

Parameters: One parameter is required for this method.

fromKey: low end point (inclusive) of the keys in the returned map.

Returns: a view of the portion of this map whose keys are greater than or equal to fromKey.

Throws:

1. ClassCastException - if fromKey is not compatible with  this map's comparator.

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

3. IllegalArgumentException - if this map itself has a restricted range, and fromKey lies outside the bounds of the range

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMaptailMap {
    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 fromKey = 2;

        System.out.println(treeMap.tailMap(fromKey));

    }
}

Output:

{2=Hello, 6=C++, 11=Java, 23=Program, 25=Program}


Approach 2: NullPointerException 

Java

import java.util.TreeMap;

public class TreeMaptailMap {
    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 fromKey = null;

        System.out.println(treeMap.tailMap(fromKey));

    }
}

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$NavigableSubMap.<init>(TreeMap.java:1644) at java.base/java.util.TreeMap$AscendingSubMap.<init>(TreeMap.java:2129) at java.base/java.util.TreeMap.tailMap(TreeMap.java:1210) at java.base/java.util.TreeMap.tailMap(TreeMap.java:1245)


No comments:

Post a Comment