Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java
treeset

What is the TreeSet.first() function in Java?

Vinisha Maheshwari

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The TreeSet.first() method obtains the first element in the TreeSet.

This method is present in the TreeSet class inside the java.util package.

Parameters

The TreeSet.first() method does not take any parameters.

Return

  • Element: It returns the lowest member of the TreeSet.

Example

Let’s understand with the help of an example.

We have a TreeSet: [1,8,5,3,9]

The first element in the TreeSet is 1.

The result of the TreeSet.first() method is 1.

Note: When we add the elements in the TreeSet, they get stored in the sorted form. If the TreeSet is of String type, the elements get stored in alphabetical order, irrespective of string length.

Code

Let’s take a look at the code snippet below.

import java.io.*;
import java.util.TreeSet;
class Main
{
public static void main(String args[])
{
TreeSet<Integer> tree_set = new TreeSet<Integer>();
tree_set.add(1);
tree_set.add(8);
tree_set.add(5);
tree_set.add(3);
tree_set.add(0);
System.out.println("First element of TreeSet is " + tree_set.first());
}
}
Using TreeSet.first() function in Java

Explanation

  • In lines 1 and 2, we import the required packages and classes.

  • In line 4, we create a Main class.

  • In line 6, we create a main function.

  • In line 8, we declare a TreeSet of Integer type.

  • In lines 9 to 13, we add the elements into the TreeSet by using the TreeSet.add() method.

  • In line 14, we get the lowest member or the first element of the TreeSet using TreeSet.first() method and display the result with a message.

In this way, we can use the TreeSet.first() method to get the first element of the TreeSet.

RELATED TAGS

communitycreator
java
treeset

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring