Home » Java programming language

Java TreeSet first() Method with Example

TreeSet Class first() method: Here, we are going to learn about the first() method of TreeSet Class with its syntax and example.
Submitted by Preeti Jain, on February 20, 2020

TreeSet Class first() method

  • first() method is available in java.util package.
  • first() method is used to retrieve the first lowest element in this TreeSet.
  • first() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • first() method may throw an exception at the time of returning the first least object in this TreeSet.
    NoSuchElementException – This exception may throw when this TreeSet is “blank”.


    public Element first();


  • It does not accept any parameter.

Return value:

The return type of the method is Element, it gets the first least element exists in this TreeSet.


// Java program to demonstrate the example 
// of Element first() method of TreeSet 

import java.util.*;

public class FirstOfTreeSet {
    public static void main(String[] args) {
        // Instantiates a TreeSet object
        TreeSet < String > tree_set = new TreeSet < String > ();

        // By using add() method is to add
        // the given object of this TreeSet 

        // Display TreeSet
        System.out.println("TreeSet: " + tree_set);

        // By using first() method is to return
        // the first least element exists in this TreeSet
        Object first_least = tree_set.first();

        // Display first_least
        System.out.println("tree_set.first(): " + first_least);


TreeSet: [C, C++, JAVA, PHP, SFDC]
tree_set.first(): C

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.