SortedSet tailSet() method in Java
Last Updated :
30 Sep, 2018
The tailSet() method of SortedSet interface in Java is used to return a view of the portion of this set whose elements are greater than or equal to the parameter fromElement.
- 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 tailSet(E fromElement)
Where, E is the type of element maintained by this Set.
Parameters: This function accepts a single parameter fromElement which represent the low endpoint (inclusive) of the returned set.
Return Value: It returns the elements which are greater than or equal to the given argument fromElement.
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:
import java.util.SortedSet;
import java.util.TreeSet;
public class Main {
public static void main(String[] args)
{
SortedSet<Integer> s = new TreeSet<>();
s.add( 1 );
s.add( 5 );
s.add( 2 );
s.add( 3 );
s.add( 9 );
System.out.print( "Elements greater than or equal to 5 in set are : "
+ s.tailSet( 5 ));
}
}
|
Output:
Elements greater than or equal to 5 in set are : [5, 9]
Program 2:
import java.util.SortedSet;
import java.util.TreeSet;
public class Main {
public static void main(String[] args)
{
SortedSet<String> s = new TreeSet<>();
s.add( "Geeks" );
s.add( "For" );
s.add( "Geeks" );
s.add( "Code" );
s.add( "It" );
System.out.print( "Element greater than or equal to G in set is : "
+ s.tailSet( "G" ));
}
}
|
Output:
Element greater than or equal to G in set is : [Geeks, It]
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/SortedSet.html#tailSet(E)
Share your thoughts in the comments
Please Login to comment...