TreeSet ceiling() method in java

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

TreeSet ceiling() method in java

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

Syntax:

public E ceiling(E e)

Parameters:

e the value to match.

Returns:

the least element greater than or equal to e, or null if there is no such element.

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.

Also read – TreeSet in java

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

import java.util.TreeSet;
public class TreeSetCeilingMethodExample
{
   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("TreeSet values: " + ts);
         // get ceiling value for 65 using ceiling() method
         int value = ts.ceiling(65);
         // print the ceiling value
         System.out.println("Ceiling value for 65: " + value);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}


Output:

TreeSet values: [50, 60, 70, 80]
Ceiling value for 65: 70


Let’s example on TreeSet ceiling() method for NullPointerException.

import java.util.TreeSet;
public class TreeSetCeilingMethodExample
{
   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("TreeSet values: " + ts);
         // get ceiling value for null using ceiling() method
         System.out.println("compare with null value: ");
         int value = ts.ceiling(null);
         // print the ceiling value
         System.out.println("Ceiling value for null: " + value);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}


Output:

TreeSet values: [50, 60, 70, 80]
compare with null value:
Exception: java.lang.NullPointerException