Java TreeSet - first() Method
The java.util.TreeSet.first() method returns the first (lowest) element currently in this set.
Syntax
public E first()
Here, E is the type of element maintained by the container.
Parameters
No parameter is required.
Return Value
Returns the first (lowest) element currently in this set.
Exception
Throws NoSuchElementException, if this set is empty.
Example:
In the example below, the java.util.TreeSet.first() method is used to get the value of first (lowest) element of the treeset.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating a treeset TreeSet<Integer> MySet = new TreeSet<Integer>(); //populating the set MySet.add(40); MySet.add(20); MySet.add(10); MySet.add(30); //printing the set System.out.println("MySet contains: " + MySet); //printing the first element System.out.println("First Element of the Set: " + MySet.first()); } }
The output of the above code will be:
MySet contains: [10, 20, 30, 40] First Element of the Set: 10
❮ Java.util - TreeSet