TreeMap floorKey(K key) method in java

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

TreeMap floorKey(K key) method in java

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

Syntax:

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

import java.util.TreeMap;
public class TreeMapFloorkeyExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(60, "apple");
      tm.put(10, "banana");
      tm.put(50, "cherry");
      tm.put(30, "fig");
      tm.put(80, "grape");
      tm.put(90, "kiwifruit");
      System.out.println("Checking greatest key less than or equal to 40: ");
      System.out.println("Value is: " + tm.floorKey(40));
   }
}

Output:

Checking greatest key less than or equal to 40:
Value is: 30


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

import java.util.TreeMap;
public class TreeMapFloorkeyExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(60, "apple");
      tm.put(10, "banana");
      tm.put(50, "cherry");
      tm.put(30, "fig");
      tm.put(80, "grape");
      tm.put(90, "kiwifruit");
      // printing values of TreeMap
      System.out.println("TreeMap: " + tm);
      try
      {
         // passing null as parameter to floorKey() method
         System.out.println(tm.floorKey(null));
      }
      catch(Exception ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}

Output:

TreeMap: {10=banana, 30=fig, 50=cherry, 60=apple, 80=grape, 90=kiwifruit}
Exception: java.lang.NullPointerException


Also read – random number generator in java