TreeMap lowerKey(K key) method in java

Let’s learn TreeMap lowerKey(K key) method in java.

TreeMap lowerKey(K key) method in java

lowerKey(K key) method of TreeMap class returns the greatest key strictly less than the given key, or null if there is no such key.

Syntax:

public K lowerKey(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 lowerKey(K key) method.

import java.util.TreeMap;
public class TreeMapLowerKeyMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(8, "mango");
      tm.put(5, "apple");
      tm.put(3, "watermelon");
      tm.put(7, "pineapple");
      tm.put(6, "orange");
      tm.put(9, "grapes");
      System.out.println("TreeMap: " + tm.toString());
      // here 10 is not available it returns 9
      System.out.print("Lower Key Entry of Element 10 is: ");
      System.out.println(tm.lowerKey(10));
      System.out.print("Lower Key Entry of Element 5 is: ");
      System.out.println(tm.lowerKey(5));
   }
}


Output:

TreeMap: {3=watermelon, 5=apple, 6=orange, 7=pineapple, 8=mango, 9=grapes}
Lower Key Entry of Element 10 is: 9
Lower Key Entry of Element 5 is: 3


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

import java.util.TreeMap;
public class TreeMapLowerKeyMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(8, "mango");
      tm.put(5, "apple");
      tm.put(3, "watermelon");
      tm.put(7, "pineapple");
      tm.put(6, "orange");
      tm.put(9, "grapes");
      System.out.println("TreeMap: " + tm.toString());
      try
      {
         // pass null as parameter to lowerKey() method
         System.out.println(tm.lowerKey(null));
      }
      catch(Exception ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}


Output:

TreeMap: {3=watermelon, 5=apple, 6=orange, 7=pineapple, 8=mango, 9=grapes}
Exception: java.lang.NullPointerException