![]() |
VOOZH | about |
The first method in Java’s TreeSet returns the lowest element in the set based on its natural ordering or a custom comparator.
TreeSet<E> treeSet;
E firstElement = treeSet.first();
Note: TreeSet automatically sorts elements in ascending order, so first() always returns the element at the beginning of this order.
Example 1: Using first() with Integers
TreeSet: [3, 8, 10, 25] First (Lowest) Element: 3
Example 2: Using first() with Strings
TreeSet: [Alice, Bob, Diana, John] First (Lowest) Element: Alice
Example 3: Using first() with a Custom Comparator
TreeSet (Descending Order): [15, 10, 5] First Element (in Descending Order): 15
Example 4: When TreeSet is Empty
Exception: java.util.NoSuchElementException