Java TreeSet comparator() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
TreeSet

Definition

In Java, comparator() returns the Comparator sorting the TreeSet, or null when it uses natural ordering (Comparable).

Checking comparator() lets you reuse a set's ordering rule when creating a second TreeSet and explains why descendingSet() always has a non-null comparator.

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 comparator() on any TreeSet or SortedSet.

Java
TreeSet<Integer> natural = new TreeSet<>();
Comparator<? super Integer> c1 = natural.comparator();   // null

TreeSet<Integer> desc = new TreeSet<>(Comparator.reverseOrder());
Comparator<? super Integer> c2 = desc.comparator();      // reverseOrder comparator
CallWhat it does
set.comparator()Returns the custom Comparator, or null for natural order.
new TreeSet<>(set.comparator())Creates an empty set with the same sort rule (even when null).
set.descendingSet().comparator()Always non-null: returns the reversed comparator.
Comparator.nullsFirst(c)Wraps a comparator so null elements are allowed.

Passing null to new TreeSet<>((Comparator<T>) null) selects natural ordering—so new TreeSet<>(other.comparator()) works for both custom and natural sets.

Library declarations
Java
// java.util.TreeSet<E>
public Comparator<? super E> comparator()

// Declared in SortedSet<E>

Parameters

ParameterDescription
Nonecomparator() takes no parameters.

Return Value

Return ValueDescription
Comparator<? super E>The comparator passed at construction (or reversed comparator on descendingSet()).
nullIf the set uses the elements' natural ordering.

Compare with Similar Methods

Constructors and methods related to TreeSet ordering:

MethodHow it differs
descendingSet()Reverses the set's comparator in a live view.
clone()Copies elements while keeping the same comparator.
add(e)Uses the comparator to detect duplicates (compare == 0).
Collections.reverseOrder()Standard descending comparator often returned by comparator().

Java Examples

Example 1 — Compare Natural Ordering (null) Against Custom Comparators

Inspect comparator() on a natural-order set, a case-insensitive set, and a descending view.

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

public class TreeSetComparatorInspect {
    public static void main(String[] args) {
        TreeSet<String> natural = new TreeSet<>(Arrays.asList("b", "a"));
        TreeSet<String> ignoreCase = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        ignoreCase.addAll(natural);

        System.out.println("natural comparator:    " + natural.comparator());
        System.out.println("CASE_INSENSITIVE?      " + (ignoreCase.comparator() == String.CASE_INSENSITIVE_ORDER));
        System.out.println("descending view null?  " + (natural.descendingSet().comparator() == null));
    }
}

How It Works

  1. Natural order returns null. No explicit comparator was supplied to natural, so comparator() returns null.
  2. Same instance returned. ignoreCase.comparator() returns the exact String.CASE_INSENSITIVE_ORDER comparator.
  3. Reversed view is always custom. Even for a natural-order set, descendingSet().comparator() returns a non-null reverse comparator.

Example 2 — Create an Empty Set With the Same Comparator

Write a helper that builds a fresh empty TreeSet inheriting whatever ordering rule an input set uses.

Java
import java.util.Arrays;
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

public class TreeSetComparatorReuse {
    static <E> TreeSet<E> emptyLike(SortedSet<E> template) {
        return new TreeSet<>(template.comparator());
    }

    public static void main(String[] args) {
        TreeSet<Integer> desc = new TreeSet<>(Comparator.reverseOrder());
        desc.addAll(Arrays.asList(5, 1, 9));

        TreeSet<Integer> filtered = emptyLike(desc);
        for (int n : desc) {
            if (n >= 5) {
                filtered.add(n);
            }
        }
        System.out.println("filtered keeps reverse order: " + filtered);

        TreeSet<Integer> nat = new TreeSet<>(Arrays.asList(5, 1, 9));
        TreeSet<Integer> natCopy = emptyLike(nat);
        natCopy.addAll(nat);
        System.out.println("natural template:             " + natCopy);
    }
}

How It Works

  1. One constructor handles both. Passing template.comparator() works whether it is a custom comparator or null.
  2. Descending rule preserved. Adding 9 and 5 to filtered outputs [9, 5] because it inherited reverseOrder().
  3. Natural rule preserved too. When nat.comparator() returns null, new TreeSet<>((Comparator) null) uses natural order.

Example 3 — Avoid Dropping Equal-Length Words With thenComparing()

See how a length-only comparator collapses equal-length words, and fix it with thenComparing().

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

public class TreeSetComparatorTieBreak {
    public static void main(String[] args) {
        TreeSet<String> byLength = new TreeSet<>(Comparator.comparingInt(String::length));
        byLength.addAll(Arrays.asList("pear", "fig", "plum", "kiwi"));
        System.out.println("length only (drops plum, kiwi): " + byLength);

        @SuppressWarnings("unchecked")
        Comparator<String> current = (Comparator<String>) byLength.comparator();
        Comparator<String> full = current.thenComparing(Comparator.naturalOrder());
        TreeSet<String> fixed = new TreeSet<>(full);
        fixed.addAll(Arrays.asList("pear", "fig", "plum", "kiwi"));
        System.out.println("with tie-breaker: " + fixed);
    }
}

How It Works

  1. Equal length equals zero. Under comparingInt(String::length), "plum" and "kiwi" both have length 4 like "pear", so they are dropped as duplicates.
  2. Chain a tie-breaker. Calling .thenComparing(Comparator.naturalOrder()) on the retrieved comparator breaks length ties alphabetically.
  3. All four words kept. Now fixed sorts by length first (fig) and alphabetically within length 4 (kiwi, pear, plum).

Frequently Asked Questions

null means the TreeSet was created without a custom Comparator and uses the elements natural ordering (Comparable).
Pass original.comparator() to the new TreeSet constructor, or pass the SortedSet itself via new TreeSet<>(original).
Because descendingSet() reverses the natural order (or custom comparator), so it returns a non-null reverse Comparator.
TreeSet treats the second object as a duplicate and ignores it on add(). Add thenComparing() if you only want truly equal elements treated as duplicates.
No. The comparator is fixed at creation time; create a new TreeSet with the new comparator and call addAll(oldSet).

Next: contains()

Test in O(log n) time whether a matching element is in the set.

contains() 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.

12 people found this page helpful