TreeSet headSet() method in java

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

TreeSet headSet() method in java

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

Syntax:

public NavigableSet<E> headSet(E toElement, boolean inclusive)

Parameters:

toElement high endpoint of the returned set.

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

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, boolean inclusive) method.

import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetHeadSetMethodExample
{
   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 for 5 inclusive true
      hs = (TreeSet)ts.headSet(5, true);
      // create iterator
      Iterator<Integer> iterate = hs.iterator();
      System.out.println("TreeSet data for '5' inclusive TRUE: ");
      while(iterate.hasNext())
      {
         System.out.println(iterate.next() + " ");
      }
      // get values for 5 inclusive false
      hs = (TreeSet)ts.headSet(5, false);
      iterate = hs.iterator();
      System.out.println("TreeSet data for '5' inclusive FALSE: ");
      while(iterate.hasNext())
      {
         System.out.println(iterate.next() + " ");
      }
   }
}


Output:

TreeSet data for ‘5’ inclusive TRUE:
1
2
3
4
5
TreeSet data for ‘5’ inclusive FALSE:
1
2
3
4