VOOZH about

URL: https://www.geeksforgeeks.org/java/sortedset-subset-method-in-java/

⇱ SortedSet subSet() method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.
  • The set returned by this method is backed by this set, so changes in the returned set are reflected in this set, and vice-versa.
  • The set returned by this method supports all optional set operations that this set supports.
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:
  • ClassCastException : It throws a ClassCastException if fromElement is not compatible with this set's comparator (or, if the set has no comparator, if fromElement does not implement Comparable).
  • NullPointerException : It throws a NullPointerException if the parameter fromElement is null.
  • IllegalArgumentException : It throws an IllegalArgumentException this set itself has a restricted range, and the parameter fromElement lies outside the bounds of the range.
Below programs illustrate the above method: Program 1:
Output:
Elements range between 2 and 9 in set are : [2, 3, 5]
Program 2:
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)
Comment