TreeMap lowerEntry(K key) method in java

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

TreeMap lowerEntry(K key) method in java

lowerEntry(K key) method of TreeMap class returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.

Syntax:

public Map.Entry<K, V> lowerEntry(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.

Now let’s see example on TreeMap lowerEntry(K key) method.

import java.util.TreeMap;
public class TreeMapLowerEntryMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(7, "red");
      tm.put(3, "green");
      tm.put(6, "violet");
      tm.put(5, "blue");
      tm.put(4, "yellow");
      // get lower entry
      System.out.println("Check lower entry in given TreeMap");
      System.out.println("Value is: "+ tm.lowerEntry(5));
   }
}

Output:

Check lower entry in given TreeMap
Value is: 4=yellow


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

import java.util.Map;
import java.util.TreeMap;
public class TreeMapLowerEntryMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
         tm.put(7, "red");
         tm.put(3, "green");
         tm.put(6, "violet");
         tm.put(5, "blue");
         tm.put(4, "yellow");
         System.out.println("Given TreeMap: " + tm);
         // get lowerEntry value for null using lowerEntry() method
         System.out.println("Get lowerEntry value for value null: ");
         Map.Entry<Integer, String> value = tm.lowerEntry(null);
         System.out.println("Value is: " + value);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception : " + ex);
      }
   }
}

Output:

Given TreeMap: {3=green, 4=yellow, 5=blue, 6=violet, 7=red}
Get lowerEntry value for value NULL:
Exception : java.lang.NullPointerException


Also read – static keyword in java