In Java, size() returns the number of elements currently stored in the TreeSet as an int.
Because a TreeSet never holds duplicates, size() tells you how many distinct elements exist. On the main TreeSet it runs in constant O(1) time by reading an internal counter.
An instance method of java.util.TreeSet (Java 1.2+): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe.
Syntax
Call size() with no arguments.
Java
TreeSet<String> words = new TreeSet<>(Arrays.asList("red", "blue", "red"));
int count = words.size(); // 2 ("red" counted once)
Call
What it does
set.size()
Number of unique elements in the set.
set.isEmpty()
Preferred way to check set.size() == 0.
set.subSet(a, b).size()
Counts only elements inside the slice.
new TreeSet<>(list).size()
Counts unique elements in a list.
On a range view returned by subSet(), headSet(), or tailSet(), calling size() may need to walk the elements inside that range rather than reading a single counter.
Library declarations
Java
// java.util.TreeSet<E>
public int size()
// Declared in Set<E> and Collection<E>
Parameters
Parameter
Description
None
size() takes no parameters.
Return Value
Return Value
Description
int
The number of elements in the set (or Integer.MAX_VALUE if more exist).
View counts only its slice. Calling size() on passing counts only the four scores from 68 up to 95.
Closed range view. Setting both booleans to true lets honors count values in 85..100 inclusive.
No copying needed. Both views reflect the same backing tree without allocating new sets.
Frequently Asked Questions
It returns an int equal to the number of distinct elements currently in the TreeSet.
No. Duplicates are rejected on insertion, so size() always counts unique elements.
Yes on a main TreeSet, because the backing TreeMap stores its element count. On subSet, headSet, or tailSet views, size() may traverse elements in the range.
Arrays use the .length field and Strings use .length(); Java collections including TreeSet use the .size() method.
Prefer isEmpty(). It expresses intent more clearly and avoids scanning a range view unnecessarily.