TreeMap floorEntry() method in java

Let’s learn TreeMap floorEntry() method in java.

TreeMap floorEntry() method in java

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

Syntax:

public Map.Entry<K, V> floorEntry(K key)

Parameters:

key the key

Returns:

an entry with the greatest key less than or equal to key, or null if there is no such 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 floorEntry(K key) method.

import java.util.TreeMap;
public class TreeMapFloorEntryMethodExample
{
   public static void main(String[] args)
   {
      TreeMap<Integer, String> tm = new TreeMap<Integer, String>();
      tm.put(63, "orange");
      tm.put(50, "apple");
      tm.put(83, "watermelon");
      tm.put(86, "banana");
      tm.put(56, "mango");
      System.out.println("Check floor entry for 86: ");
      System.out.println("Value is: " + tm.floorEntry(86));
   }
}


Output:

Check floor entry for 86:
Value is: 86=banana