Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

SortedSet last() method in Java

  • Last Updated : 06 Jul, 2021

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
 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

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 lowest element from set
        System.out.print("Greatest element in set is : "
                         + s.last());
    }
}
Output: 
Greatest element in set is : 9

 

Program 2
 

Java




// Program to illustrate the last()
// method of SortedSet interface
 
import java.util.SortedSet;
import java.util.TreeSet;
 
public class GFG {
    public static void main(String args[])
    {
        // Create an empty SortedSet
        SortedSet<Integer> s = new TreeSet<>();
 
        // Trying to access element from
        // empty set
        try {
            s.last();
        }
        catch (Exception e) {
            // throws NoSuchElementException
            System.out.println("Exception: " + e);
        }
    }
}
Output: 
Exception: java.util.NoSuchElementException

 

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!