TreeSet tailSet() method in java

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

TreeSet tailSet() method in java

tailSet(E fromElement, boolean inclusive) method of TreeSet class returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.

Syntax:

public NavigableSet<E> tailSet(E fromElement, boolean inclusive)

Parameters:

fromElement low endpoint of the returned set.

inclusive true if the low endpoint is to be included in the returned view.

Throws:

ClassCastException – if fromElement is not compatible with this set’s comparator.

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

IllegalArgumentException – if this set itself has are stricted range, and fromElement lies outside the bounds of the range.

Also read – TreeSet in java

Now let’s see example on TreeSet tailSet(E fromElement, boolean inclusive) method.

import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetTailSetFromElementMethod
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      TreeSet<Integer> inclusive = new TreeSet<Integer>();
      ts.add(12);
      ts.add(22);
      ts.add(32);
      ts.add(42);
      ts.add(52);
      ts.add(62);
      ts.add(72);
      ts.add(82);
      // create tailSet
      inclusive = (TreeSet)ts.tailSet(52, true);
      // create iterator
      Iterator<Integer> iterate = inclusive.iterator();
      System.out.println("TreeSet tailSet: ");
      while(iterate.hasNext())
      {
         System.out.println(iterate.next() + " ");
      }
   }
}


Output:

TreeSet tailSet:
52
62
72
82