A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/sortedset-subset-method-in-java/ below:

SortedSet subSet() method in Java

SortedSet subSet() method in Java

Last Updated : 11 Jul, 2025

The subSet() method of

SortedSet interface in Java

is used to return a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.

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 subSet(E fromElement,
                    E toElement)

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

Parameters

: This function accepts two parameters

fromElement

and

toElement

which represent the low endpoint (

inclusive

) and high endpoint (

exclusive

) of the returned set.

Return Value

: It returns the elements which in range between

fromElement

and

toElement

passed as argument.

Exceptions

:

Below programs illustrate the above method:

Program 1

:

Java
// 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
        // ranging between the passed value
        System.out.print("Elements range between 2 and 9 in set are : "
                         + s.subSet(2, 9));
    }
}
Output:
Elements range between 2 and 9 in set are : [2, 3, 5]
Program 2

:

Java
// 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
        // ranging between the passed value
        System.out.print("Elements between C and G in set is : "
                         + s.subSet("C", "G"));
    }
}
Output:
Elements between C and G in set is : [Code, For]
Reference

:

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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4