What is TreeSet.size() function in Java?

In this shot, we will discuss how to use the TreeSet.size() method in Java. The TreeSet.size() method is present in the TreeSet class inside the java.util package and is used to obtain the number of elements in the TreeSet or the size of the TreeSet.

Parameters

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

Return value

TreeSet.size() returns the number of elements present in or the size of the TreeSet.

Example

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

  • The number of elements in the TreeSet = 5

  • The result of the TreeSet.size() method is 5

Code

Let’s have a look at the code snippet.

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("TreeSet: " + tree_set.size());
}
}

Explanation

  • In lines 1 and 2, we import the required packages and classes.
  • In line 4, we initialize a Main class.
  • In line 6, we initialize 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 with the TreeSet.add() method.
  • In line 14, we use the TreeSet.size() method to get the size of TreeSet and display the result with a message.

Free Resources