Java Utility Library

Java TreeSet - headSet() Method



The java.util.TreeSet.headSet() method returns a view of the portion of this set whose elements are strictly less than toElement. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa.

Syntax

public SortedSet<E> headSet(E toElement)

Here, E is the type of element maintained by the container.


Parameters

toElement Specify the high endpoint (exclusive) of the returned set.

Return Value

Returns a view of the portion of this set whose elements are strictly less than toElement.

Exception

  • Throws ClassCastException, if toElement is not compatible with this set's comparator (or, if the set has no comparator, if toElement does not implement Comparable).
  • Throws NullPointerException, if toElement is null and this set uses natural ordering, or its comparator does not permit null elements.
  • Throws IllegalArgumentException, if this set itself has a restricted range, and toElement lies outside the bounds of the range.

Example:

In the example below, the java.util.TreeSet.headSet() method returns a view of the portion of the given set containing elements strictly less than the specified value.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treeset
    TreeSet<Integer> Set1 = new TreeSet<Integer>();
    TreeSet<Integer> Set2 = new TreeSet<Integer>();

    //populating Set1
    Set1.add(10);
    Set1.add(20);
    Set1.add(30);
    Set1.add(40);
    Set1.add(50);

    //printing the Set1
    System.out.println("Set1 contains: " + Set1); 

    //creating the headset 
    //(limiting the value till 35)
    Set2 = (TreeSet<Integer>)Set1.headSet(35); 

    //printing the Set2
    System.out.println("Set2 contains: " + Set2);     
  }
}

The output of the above code will be:

Set1 contains: [10, 20, 30, 40, 50]
Set2 contains: [10, 20, 30]

❮ Java.util - TreeSet