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 less than (or equal to, if inclusive is true) 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 NavigableSet<E> headSet(E toElement, boolean inclusive)

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


Parameters

toElement Specify the high endpoint of the returned set.
inclusive Specify true if the high endpoint is to be included in the returned view.

Return Value

Returns a view of the portion of this set whose elements are less than (or equal to, if inclusive is true) 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 less than (or equal to, if inclusive is true) 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 30)
    Set2 = (TreeSet<Integer>)Set1.headSet(30, true); 

    //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