This example shows how to get TreeSet size using the size method in Java. The TreeSet size or length means the number of elements stored in the TreeSet object.
How to get TreeSet size in Java?
The size
method of the TreeSet class returns the size of the TreeSet object.
1 |
public int size() |
The size
method returns an int value containing the number of elements stored in the set object. It returns 0 when the TreeSet object is empty.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.TreeSet; public class TreeSetSizeExample { public static void main(String[] args) { TreeSet<Integer> tSetPrimeNumbers = new TreeSet<Integer>(); /* * To get the TreeSet length or size, use the size method */ //this will return 0 as the TreeSet is empty int size = tSetPrimeNumbers.size(); System.out.println("Size: " + size); //add elements tSetPrimeNumbers.add(2); tSetPrimeNumbers.add(3); //this will return 2 as there are 2 elements in TreeSet size = tSetPrimeNumbers.size(); System.out.println("Size: " + size); } } |
Output
1 2 |
Size: 0 Size: 2 |
How to check if TreeSet is empty using the size method?
The size
method returns 0 if there are no elements in the TreeSet. We can compare the return value of the size
method with 0 to check if the TreeSet is empty or not as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.TreeSet; public class TreeSetSizeExample { public static void main(String[] args) { TreeSet<Integer> tSetPrimeNumbers = new TreeSet<Integer>(); //this will return true as the TreeSet is empty System.out.println("Empty? " + (tSetPrimeNumbers.size() == 0) ); //add elements tSetPrimeNumbers.add(2); tSetPrimeNumbers.add(3); tSetPrimeNumbers.add(5); //this will return false as there are 3 elements in TreeSet System.out.println("Empty? " + (tSetPrimeNumbers.size() == 0) ); } } |
Output
1 2 |
Empty? true Empty? false |
Please also visit how to check if TreeSet is empty in Java example to know more.
This example is a part of the Java TreeSet Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 TreeSet