TreeMap higherKey() method in java

Let’s learn TreeMap higherKey() method in java.

TreeMap higherKey() method in java

higherKey(K key) method of TreeMap class returns the least key strictly greater than the given key, or null if there is no such key.

Syntax:

public K higherKey(K key)

Parameters:

key the key

Throws:

ClassCastException – if the specified key cannot be compared with the keys currently in the map.

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

Also read – TreeMap in java

Now let’s see example on TreeMap higherKey() method.

import java.util.TreeMap;
public class TreeMapHigherKeyMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
         tm.put(6, "green");
         tm.put(3, "violet");
         tm.put(2, "red");
         tm.put(8, "yellow");
         tm.put(5, "blue");
         System.out.println("Given TreeMap: " + tm);
         // getting higher key value for 5 using higherKey() method
         int value = tm.higherKey(5);
         System.out.println("The higherKey value for 5: " + value);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}


Output:

Given TreeMap: {2=red, 3=violet, 5=blue, 6=green, 8=yellow}
The higherKey value for 5: 6


Let’s see example on TreeMap higherKey(K key) method for NullPointerException.

import java.util.TreeMap;
public class TreeMapHigherKeyMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
         tm.put(6, "green");
         tm.put(3, "violet");
         tm.put(2, "red");
         tm.put(8, "yellow");
         tm.put(5, "blue");
         System.out.println("Given TreeMap: " + tm);
         // getting higher key value for null using higherKey() method
         System.out.println("The higherKey value for null: ");
         int value = tm.higherKey(null);
         System.out.println("Value is: " + value);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}


Output:

Given TreeMap: {2=red, 3=violet, 5=blue, 6=green, 8=yellow}
The higherKey value for null:
Exception: java.lang.NullPointerException