The last() method of SortedSet interface in Java is used to return the last i.e., the highest element currently in this set.
Syntax:
E last()
Where, E is the type of element maintained by this Set.
Parameters: This function does not accepts any parameter.
Return Value: It returns the last or the highest element currently in the set.
Exceptions: It throws NoSuchElementException, if the set is empty.
Below programs illustrate the above method:
Program 1:
Java
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( "Greatest element in set is : "
+ s.last());
}
}
|
Output:
Greatest element in set is : 9
Program 2:
Java
import java.util.SortedSet;
import java.util.TreeSet;
public class GFG {
public static void main(String args[])
{
SortedSet<Integer> s = new TreeSet<>();
try {
s.last();
}
catch (Exception e) {
System.out.println( "Exception: " + e);
}
}
}
|
Output:
Exception: java.util.NoSuchElementException
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/SortedSet.html#last()
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
06 Jul, 2021
Like Article
Save Article