TreeSet lower() method in java

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

TreeSet lower() method in java

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

Syntax:

public E lower(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.

Also read – TreeSet in java

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

import java.util.TreeSet;
public class TreeSetLowerMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(15);
      ts.add(8);
      ts.add(3);
      ts.add(2);
      ts.add(10);
      ts.add(5);
      System.out.println(ts.lower(18));
   }
}


Output:

15


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

import java.util.TreeSet;
public class TreeSetLowerMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      try
      {
         ts.add(15);
         ts.add(8);
         ts.add(3);
         ts.add(2);
         ts.add(10);
         ts.add(5);
         System.out.println(ts.lower(null));
      }
      catch(Exception ex)
      {
         ex.printStackTrace();
      }
   }
}


Output:

java.lang.NullPointerException


Now let’s see example on TreeSet lower() method for ClassCastException.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
public class TreeSetLowerMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<List> ts = new TreeSet<List>();
      List<Integer> li1 = new LinkedList<Integer>();
      li1.add(10);
      li1.add(20);
      ts.add(li1);
      List<Integer> li2 = new LinkedList<Integer>();
      li2.add(30);
      li2.add(40);
      List<Integer> li3 = new ArrayList<Integer>();
      li2.add(50);
      li2.add(60);
      try
      {
         System.out.println(ts.lower(li3));
      }
      catch(Exception ex)
      {
         System.out.println(ex);
      }
   }
}


Output:

Exception in thread “main” java.lang.ClassCastException: class java.util.LinkedList cannot be cast to class java.lang.Comparable