TreeSet tailSet() method in java

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

TreeSet tailSet() method in java

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

Syntax:

public SortedSet<E> tailSet(E fromElement)

Parameters:

fromElement low endpoint (inclusive) of the returned set.

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) method.

import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetTailSetMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      TreeSet<Integer> tail = new TreeSet<Integer>();
      ts.add(11);
      ts.add(21);
      ts.add(31);
      ts.add(41);
      ts.add(51);
      ts.add(61);
      ts.add(71);
      ts.add(81);
      // create tailSet
      tail = (TreeSet)ts.tailSet(41);
      // create iterator
      Iterator<Integer> iterate = tail.iterator();
      System.out.println("TreeSet tailSet: ");
      while(iterate.hasNext())
      {
         System.out.println(iterate.next() + " ");
      }
   }
}


Output:

TreeSet tailSet:
41
51
61
71
81

1 Comment

Comments are closed.