Java TreeSet - size() Method
The java.util.TreeSet.size() method returns the total number of elements present in this set (its cardinality).
Syntax
public int size()
Parameters
No parameter is required.
Return Value
Returns the number of elements in this set (its cardinality).
Exception
NA
Example:
In the example below, the java.util.TreeSet.size() method is used to find out the total number of elements in the given set.
import java.util.*; public class MyClass { public static void main(String[] args) { //creating treeset TreeSet<Integer> MySet = new TreeSet<Integer>(); //populating the set MySet.add(10); MySet.add(20); MySet.add(30); MySet.add(40); System.out.println("Size of MySet: "+ MySet.size()); //adding one more element in the set MySet.add(50); System.out.println("Size of MySet: "+ MySet.size()); } }
The output of the above code will be:
Size of MySet: 4 Size of MySet: 5
❮ Java.util - TreeSet