treemap higherkey code example

Example 1: TreeMap higherKey() method in java

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);
      }
   }
}

Example 2: TreeMap higherKey() method in java

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);
      }
   }
}

Tags:

Java Example