Java TreeSet first() Method
Example
Get the first 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.first());
}
}
Definition and Usage
The first() method returns the first item in the set. A TreeSet keeps its items sorted, so this is the lowest item (for text, the one that comes first in alphabetical order).
If the set is empty, the method throws a NoSuchElementException.
Tip: Use the last() method to get the last item.
Syntax
public T first()
T refers to the data type of items in the set.
Parameter Values
None.
Technical Details
| Returns: | The first (lowest) item in the set. |
|---|---|
| Throws: | NoSuchElementException - if the set is empty. |
Related Pages
❮ TreeSet Methods