The first method in Java’s TreeSet returns the lowest element in the set based on its natural ordering or a custom comparator.
Syntax
TreeSet<E> treeSet;
E firstElement = treeSet.first();
- Parameters: This method does not take any parameters.
- Return Value: Returns the first (lowest) element (smallest value in case of integers and lexicographically smallest in case of strings)
- Throws: If the set is empty, it throws a NoSuchElementException
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
import java.util.TreeSet;
public class GFG{
public static void main(String[] args){
TreeSet<Integer> numbers = new TreeSet<>();
numbers.add(10);
numbers.add(3);
numbers.add(25);
numbers.add(8);
System.out.println("TreeSet: " + numbers);
// Get the first element
int firstElement = numbers.first();
System.out.println("First (Lowest) Element: " + firstElement);
}
}
Output
TreeSet: [3, 8, 10, 25] First (Lowest) Element: 3
Example 2: Using first() with Strings
import java.util.TreeSet;
public class GFG{
public static void main(String[] args){
TreeSet<String> names = new TreeSet<>();
names.add("John");
names.add("Alice");
names.add("Bob");
names.add("Diana");
System.out.println("TreeSet: " + names);
// Retrieve the first element
String firstName = names.first();
System.out.println("First (Lowest) Element: " + firstName);
}
}
Output
TreeSet: [Alice, Bob, Diana, John] First (Lowest) Element: Alice
Example 3: Using first() with a Custom Comparator
import java.util.Comparator;
import java.util.TreeSet;
public class GFG {
public static void main(String[] args){
// TreeSet with descending order
TreeSet<Integer> numbers
= new TreeSet<>(Comparator.reverseOrder());
numbers.add(5);
numbers.add(15);
numbers.add(10);
System.out.println("TreeSet (Descending Order): "
+ numbers);
// Get the first element (highest due to reverse
// order)
int firstElement = numbers.first();
System.out.println(
"First Element (in Descending Order): "
+ firstElement);
}
}
Output
TreeSet (Descending Order): [15, 10, 5] First Element (in Descending Order): 15
Example 4: When TreeSet is Empty
import java.util.TreeSet;
public class GFG{
public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
try {
int firstElement = set.first();
System.out.println("First Element: " + firstElement);
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Output
Exception: java.util.NoSuchElementException