Java TreeSet last() Example

The first() method of java.util.TreeSet class will return the first (lowest) element currently in this set whereas last() method will return the last (highest) element currently in this set.

Signature

public E last() 

This method returns the last(highest) element currently in this set

Example

The following example shows the usage of java.util.TreeSet.last() method.

import java.util.TreeSet;

public class LastMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create an empty TreeSet
        TreeSet  treeSet1 = new TreeSet();
        
        // use add() method to add elements to the TreeSet
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");
        treeSet1.add("Element4");
        treeSet1.add("Element5");
        
        //get the last element of the treeset
        System.out.println("Last element of the treeset is : "+treeSet1.last());
    }
}

Output

Last element of the treeset is : Element5

Leave a Reply

Your email address will not be published. Required fields are marked *