Open In App

SortedSet headSet() method in Java

The headSet() method of SortedSet interface in Java is used to return a view of the portion of this set whose elements are strictly less than the parameter toElement.

Note: The set returned by this method will throw an IllegalArgumentException if an attempt is made to insert an element outside its range.



Syntax:

SortedSet headSet(E toElement)

Where, E is the type of element maintained by this Set.



Parameters: This function accepts a single parameter toElement which represent the high endpoint (exclusive) of the returned set.

Return Value: It returns the last or the highest element currently in the set.

Exceptions:

Below programs illustrate the above method:

Program 1:




// A Java program to demonstrate
// working of SortedSet
import java.util.SortedSet;
import java.util.TreeSet;
  
public class Main {
    public static void main(String[] args)
    {
        // Create a TreeSet and inserting elements
        SortedSet<Integer> s = new TreeSet<>();
  
        // Adding Element to SortedSet
        s.add(1);
        s.add(5);
        s.add(2);
        s.add(3);
        s.add(9);
  
        // Returning the set with elements
        // strictly less than the passed value
        System.out.print("Elements strictly less than 7 in set are : "
                         + s.headSet(7));
    }
}

Output:
Elements strictly less than 7 in set are : [1, 2, 3, 5]

Program 2:




// A Java program to demonstrate
// working of SortedSet
import java.util.SortedSet;
import java.util.TreeSet;
  
public class Main {
    public static void main(String[] args)
    {
        // Create a TreeSet and inserting elements
        SortedSet<String> s = new TreeSet<>();
  
        // Adding Element to SortedSet
        s.add("Geeks");
        s.add("For");
        s.add("Geeks");
        s.add("Code");
        s.add("It");
  
        // Returning the set with elements
        // strictly less than the passed value
        System.out.print("Element strictly less than Z in set is : "
                         + s.headSet("Z"));
    }
}

Output:
Element strictly less than Z in set is : [Code, For, Geeks, It]

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/SortedSet.html#headSet(E)


Article Tags :