Java Utility Library

Java TreeSet - last() Method



The java.util.TreeSet.last() method returns the last (highest) element currently in this set.

Syntax

public E last()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns the last (highest) element currently in this set.

Exception

Throws NoSuchElementException, if this set is empty.

Example:

In the example below, the java.util.TreeSet.last() method is used to get the value of last (highest) element of the treeset.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a treeset
    TreeSet<Integer> MySet = new TreeSet<Integer>();

    //populating the set
    MySet.add(20);
    MySet.add(40);
    MySet.add(10);
    MySet.add(30);

    //printing the set
    System.out.println("MySet contains: " + MySet); 

    //printing the last element
    System.out.println("Last Element of the Set: " + MySet.last());
  }
}

The output of the above code will be:

MySet contains: [10, 20, 30, 40]
Last Element of the Set: 40

❮ Java.util - TreeSet