TreeSet floor() method in java

Let’s learn TreeSet floor() method in java.

TreeSet floor() method in java

floor() method of TreeSet class returns the greatest element in this set less than or equal to the given element, or null if there is no such element.

Syntax:

public E floor(E e)

Parameters:

e the value to match.

Throws:

ClassCastException – if the specified element cannot be compared with the elements currently in the set.

NullPointerException – if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.

Now let’s see example on TreeSet floor() method.

import java.util.TreeSet;
public class TreeSetFloorMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         TreeSet<Integer> ts = new TreeSet<Integer>();
         ts.add(50);
         ts.add(60);
         ts.add(70);
         ts.add(80);
         System.out.println("Given TreeSet: " + ts);
         // get floor value for 65 using floor() method
         int value = ts.floor(65);
         // print floor value
         System.out.println("Floor value for 65 is : " + value);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}

Output:

Given TreeSet: [50, 60, 70, 80]
Floor value for 65 is : 60


Let’s learn TreeSet floor() method for NullPointerException.

import java.util.TreeSet;
public class TreeSetFloorMethodExample
{
   public static void main(String[] args)
   {
      try
      {
         TreeSet<Integer> ts = new TreeSet<Integer>();
         ts.add(50);
         ts.add(60);
         ts.add(70);
         ts.add(80);
         System.out.println("Given TreeSet: " + ts);
         // get floor value for null using floor() method
         System.out.println("Get floor value for null: ");
         int value = ts.floor(null);
         // print floor value
         System.out.println("Floor value for 65: " + value);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}

Output:

Given TreeSet: [50, 60, 70, 80]
Get floor value for null:
Exception: java.lang.NullPointerException


Also read – binary search in java