Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

What is TreeSet.size() 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.

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());
}
}
Using TreeSet.size() function in Java

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.

RELATED TAGS

communitycreator
java

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