Java TreeSet size() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

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)
CallWhat 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

ParameterDescription
Nonesize() takes no parameters.

Return Value

Return ValueDescription
intThe number of elements in the set (or Integer.MAX_VALUE if more exist).

Compare with Similar Methods

Ways to inspect counts or emptiness:

MethodHow it differs
isEmpty()Cleaner and often faster on range views when checking for zero.
clear()Resets size() back to 0.
toArray()Produces an array whose length equals size().
ArrayList.size()Counts every slot including duplicates.

Java Examples

Example 1 — Count Unique Visitors From Repeated Logins

Feed repeated visitor IDs into a TreeSet and check size() against total logins.

Java
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;

public class TreeSetSizeVisitors {
    public static void main(String[] args) {
        List<String> logins = Arrays.asList("u10", "u25", "u10", "u08", "u25", "u10");
        TreeSet<String> unique = new TreeSet<>(logins);

        System.out.println("total logins:    " + logins.size());
        System.out.println("unique visitors: " + unique.size());
        System.out.println("sorted ids:      " + unique);
    }
}

How It Works

  1. Duplicates collapse on insert. Six login records shrink down to three unique user IDs when loaded into the TreeSet.
  2. Distinct count in O(1). unique.size() returns 3 straight from the tree's counter.
  3. Bonus sorted list. Printing unique shows all three distinct visitors in sorted order.

Example 2 — How add(), remove(), and clear() Affect size()

Watch size() grow on new inserts, stay flat on duplicates, shrink on removal, and drop to 0 on clear.

Java
import java.util.TreeSet;

public class TreeSetSizeChanges {
    public static void main(String[] args) {
        TreeSet<Integer> pins = new TreeSet<>();
        System.out.println("start:       " + pins.size());

        pins.add(1111);
        pins.add(2222);
        pins.add(1111);
        System.out.println("after adds:  " + pins.size());

        pins.remove(9999);
        pins.remove(1111);
        System.out.println("after drops: " + pins.size());

        pins.clear();
        System.out.println("after clear: " + pins.size());
    }
}

How It Works

  1. Duplicate does not grow size. Adding 1111 twice still leaves pins.size() at 2.
  2. Missing removal leaves size unchanged. Attempting to remove 9999 changes nothing; removing 1111 drops size to 1.
  3. Clear resets to zero. pins.clear() sets the element count back to 0.

Example 3 — Count Matching Elements Inside a subSet() Slice

Slice passing exam scores from a full score set and compare the slice's size() to the full TreeSet.

Java
import java.util.Arrays;
import java.util.NavigableSet;
import java.util.TreeSet;

public class TreeSetSizeRange {
    public static void main(String[] args) {
        NavigableSet<Integer> scores = new TreeSet<>(Arrays.asList(42, 55, 68, 74, 88, 95));
        NavigableSet<Integer> passing = scores.tailSet(60, true);
        NavigableSet<Integer> honors = scores.subSet(85, true, 100, true);

        System.out.println("all scores: " + scores.size());
        System.out.println("passing (>=60): " + passing.size() + " " + passing);
        System.out.println("honors (85..100): " + honors.size() + " " + honors);
    }
}

How It Works

  1. View counts only its slice. Calling size() on passing counts only the four scores from 68 up to 95.
  2. Closed range view. Setting both booleans to true lets honors count values in 85..100 inclusive.
  3. 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.

Next: spliterator()

Get a Java 8 late-binding Spliterator with SORTED and DISTINCT traits.

spliterator() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful