TreeSet headSet(E toElement) method in java

Let’s learn TreeSet headSet(E toElement) method in java.

TreeSet headSet(E toElement) method in java

headSet(E toElement) method of TreeSet class returns a view of the portion of this set whose elements are strictly less than toElement.

Syntax:

public SortedSet<E> headSet(E toElement)

Parameters:

toElement high endpoint (exclusive) of the returned set.

Throws:

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

NullPointerException – if toElement 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 toElement lies outside the bounds of the range.

Also read – TreeSet in java

Now let’s see example on TreeSet headSet(E toElement) method.

import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetHeadSetEToElementMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      TreeSet<Integer> hs = new TreeSet<Integer>();
      ts.add(1);
      ts.add(2);
      ts.add(3);
      ts.add(4);
      ts.add(5);
      ts.add(6);
      // get values less than 5
      hs = (TreeSet)ts.headSet(5);
      // create iterator
      Iterator<Integer> iterate = hs.iterator();
      System.out.println("TreeSet data: ");
      while(iterate.hasNext())
      {
         System.out.println(iterate.next() + " ");
      }
   }
}


Output:

TreeSet data:
1
2
3
4

1 Comment

Comments are closed.