Java TreeSet first() Method Example

The first() method of java.util.TreeSet class will return the first (lowest) element currently in this set.

Signature

public E first() 

This method returns the first (lowest) element currently in this set

Example

The following example shows the usage of java.util.TreeSet.first() method.

import java.util.TreeSet;

public class FirstMethodTreeSetExample 
{
    public static void main(String args[])
    {
        // create an empty TreeSet
        TreeSet  treeSet1 = new TreeSet();
        
        // use add() method to add elements to the TreeSet
        treeSet1.add("Element1");
        treeSet1.add("Element2");
        treeSet1.add("Element3");
        treeSet1.add("Element4");
        treeSet1.add("Element5");
        
        //get the first element of the treeset
        System.out.println("First element of the treeset is : "+treeSet1.first());
    }
}

Output

First element of the treeset is : Element1

Leave a Reply

Your email address will not be published. Required fields are marked *