Java TreeSet last() Method
Example
Get the last item of a sorted set:
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
TreeSet<String> cars = new TreeSet<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
System.out.println(cars.last());
}
}
Definition and Usage
The last() method returns the last item in the set. A TreeSet keeps its items sorted, so this is the highest item (for text, the one that comes last in alphabetical order).
If the set is empty, the method throws a NoSuchElementException.
Tip: Use the first() method to get the first item.
Syntax
public T last()
T refers to the data type of items in the set.
Parameter Values
None.
Technical Details
| Returns: | The last (highest) item in the set. |
|---|---|
| Throws: | NoSuchElementException - if the set is empty. |
Related Pages
❮ TreeSet Methods