TreeSet last() method in java

Let’s learn TreeSet last() method in java.

TreeSet last() method in java

last() method of TreeSet class returns the last (highest) element currently in this set.

Syntax:

public E last()

Throws:

NoSuchElementException – if this set is empty.

Also read – TreeSet in java

Now let’s see example on TreeSet last() method.

import java.util.TreeSet;
public class TreeSetLastMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(58);
      ts.add(42);
      ts.add(29);
      ts.add(10);
      // print last highest element
      System.out.println("Last highest element is: " + ts.last());
   }
}


Output:

Last highest element is: 58


Let’s see example on TreeSet last() method when elements are String types.

import java.util.TreeSet;
public class TreeSetLastMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<String> ts = new TreeSet<String>();
      ts.add("grapes");
      ts.add("banana");
      ts.add("watermelon");
      ts.add("apple");
      // print last highest element
      System.out.println("Last highest element is: " + ts.last());
   }
}


Output:

Last highest element is: watermelon