TreeMap floorKey() and ceilingKey() example

FloorKey

The floorKey method is used to return the greatest key less than or equal to the given key, or null if there is no such key. Following is the declaration of floorKey method. The method call returns the greatest key less than or equal to key, or null if there is no such key.

public K floorKey(K key)

Exception

  • ClassCastException − This exception is thrown if the specified key cannot be compared with the keys currently in the map.

  • NullPointerException − This exception is thrown if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.

The following example shows the usage of java.util.TreeMap.floorKey() method.

import java.util.*;

public class TreeMapDemo {
   public static void main(String[] args) {

      // creating tree map 
      TreeMap<Integer, String> treemap = new TreeMap<Integer, String>();

      // populating tree map
      treemap.put(2, "two");
      treemap.put(1, "one");
      treemap.put(3, "three");
      treemap.put(6, "six");
      treemap.put(5, "five");

      System.out.println("Checking greatest key less than or equal to 4");
      System.out.println("Value is: "+ treemap.floorKey(4));
   }    
}

Let us compile and run the above program, this will produce the following result.

Checking greatest key less than or equal to 4
Value is: 3

CeilingKey

The ceilingKey method is used to return the least key greater than or equal to the given key, or null if there is no such key. Following is the declaration for ceilingKey() method. The method call returns the least key greater than or equal to key, or null if there is no such key.

public K ceilingKey(K key)

Exception

  • ClassCastException − It throws the exception if the specified key cannot be compared with the keys currently in the map.

  • NullPointerException − It throws the exception if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys.

The following example shows the usage of java.util.TreeMap.ceilingKey() method.

import java.util.*;

public class TreeMapDemo {
   public static void main(String[] args) {
      
      // creating tree map 
      NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>();

      // populating tree map
      treemap.put(2, "two");
      treemap.put(1, "one");
      treemap.put(3, "three");
      treemap.put(6, "six");
      treemap.put(5, "five");

      System.out.println("Ceiling key entry for 4: "+ treemap.ceilingKey(4));
      System.out.println("Ceiling key entry for 5: "+ treemap.ceilingKey(5));
      System.out.println("Ceiling key entry for 7: "+ treemap.ceilingKey(7));
   }    
}

Let us compile and run the above program, this will produce the following result.

Ceiling key entry for 4: 5
Ceiling key entry for 5: 5
Ceiling key entry for 7: null

 

Core Java Collections Map