Java TreeMap comparator() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
java.util.TreeMap

Definition

In Java, comparator() returns the Comparator a TreeMap uses to order its keys. If the map was created without one, it uses the keys' natural ordering (compareTo) and the method returns null.

The method comes from the SortedMap interface. It returns the very object passed to the constructor, so you can compare it with == or reuse it to compare keys the same way the map does.

An instance method of java.util.TreeMap, part of TreeMap since Java 1.2. A TreeMap keeps its key/value pairs sorted by key in a red-black tree, so lookups and updates take O(log n) time; it is not thread-safe.

Syntax

No arguments; returns the comparator or null.

Java
TreeMap<Integer, String> natural = new TreeMap<>();
TreeMap<Integer, String> reversed = new TreeMap<>(Comparator.reverseOrder());
natural.comparator();    // null
reversed.comparator();   // the reverse-order comparator
CallWhat it does
map.comparator() == nulltrue for natural ordering.
map.comparator().compare(a, b)Compares two keys like the map does (only if not null).
new TreeMap<>(sortedMap)Copies and keeps the comparator.

Do not print a comparator: its toString() is an internal class name and differs between JDKs. Test it with == null or == against a known comparator instead.

Library declarations
Java
// java.util.TreeMap<K, V>
public Comparator<? super K> comparator()

// Declared in SortedMap<K, V>

Parameters

ParameterDescription
Nonecomparator() takes no parameters.

Return Value

Return ValueDescription
Comparator<? super K>The comparator given to the constructor (or copied from a SortedMap).
nullThe map uses natural ordering.

Compare with Similar Methods

Ordering-related tools:

MethodHow it differs
descendingMap()Reverses the order without a new comparator.
clone()Copies the map together with its comparator.
put(k, v)Uses the comparator to place and match keys.
Collections.reverseOrder()Builds a reversing comparator to pass in.

Java Examples

Example 1 — Tell Natural and Custom Ordering Apart

Two lap-time maps, one natural and one reversed, filled with the same keys.

Java
import java.util.Comparator;
import java.util.TreeMap;

public class TreeMapComparatorCheck {
    public static void main(String[] args) {
        TreeMap<Integer, String> natural = new TreeMap<>();
        TreeMap<Integer, String> reversed = new TreeMap<>(Comparator.reverseOrder());
        for (int lap = 1; lap <= 3; lap++) {
            natural.put(lap, "lap " + lap);
            reversed.put(lap, "lap " + lap);
        }
        System.out.println("natural comparator is null: " + (natural.comparator() == null));
        System.out.println("reversed comparator is null: " + (reversed.comparator() == null));
        System.out.println("natural first: " + natural.firstKey() + ", reversed first: " + reversed.firstKey());
    }
}

How It Works

  1. No comparator given. natural relies on Integer.compareTo, so comparator() reports null.
  2. A comparator was given. reversed holds the Comparator.reverseOrder() object, so the result is not null.
  3. Visible effect. The same keys 1 to 3 start at 1 in one map and at 3 in the other, because "first" means "smallest by the comparator".

Example 2 — Compare Titles Exactly Like the Map Does

A bookshelf ignores case. Fetch its comparator and use it outside the map.

Java
import java.util.Comparator;
import java.util.TreeMap;

public class TreeMapComparatorReuse {
    public static void main(String[] args) {
        TreeMap<String, Integer> shelf = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        shelf.put("dune", 1965);
        shelf.put("Emma", 1815);
        System.out.println(shelf);

        Comparator<? super String> order = shelf.comparator();
        System.out.println("same object: " + (order == String.CASE_INSENSITIVE_ORDER));
        System.out.println("\"apple\" before \"Banana\": " + (order.compare("apple", "Banana") < 0));
        System.out.println("\"DUNE\" equals \"dune\" here: " + (order.compare("DUNE", "dune") == 0));
    }
}

How It Works

  1. Shelf order ignores case. dune prints before Emma because d comes before e once case is ignored; natural order would put Emma first.
  2. The same instance. comparator() hands back exactly String.CASE_INSENSITIVE_ORDER, so == is true.
  3. Consistent decisions. Using order.compare elsewhere, "apple" sorts before "Banana" and "DUNE" counts as the same title as "dune", just as inside the map.

Example 3 — Which Copy Keeps the Comparator?

Copy a case-insensitive map twice: once as a TreeMap and once through a Map variable.

Java
import java.util.Map;
import java.util.TreeMap;

public class TreeMapComparatorCopies {
    public static void main(String[] args) {
        TreeMap<String, Integer> relaxed = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        relaxed.put("banana", 3);
        relaxed.put("Apple", 5);
        relaxed.put("Cherry", 1);

        TreeMap<String, Integer> sortedCopy = new TreeMap<>(relaxed);
        Map<String, Integer> asMap = relaxed;
        TreeMap<String, Integer> mapCopy = new TreeMap<>(asMap);

        System.out.println("SortedMap copy keeps comparator: " + (sortedCopy.comparator() != null) + " " + sortedCopy);
        System.out.println("Map copy keeps comparator: " + (mapCopy.comparator() != null) + " " + mapCopy);
    }
}

How It Works

  1. Constructor chosen at compile time. relaxed is declared as a TreeMap, so Java picks the TreeMap(SortedMap) constructor, which copies the comparator.
  2. A Map variable hides it. asMap has the static type Map, so TreeMap(Map) is called; that constructor always starts with natural ordering.
  3. The order shows it. The second copy prints Cherry before banana, because uppercase C sorts before lowercase b in natural String order.

Frequently Asked Questions

null. Natural ordering means the keys' own compareTo method is used.
You can, but the text is an internal class name that differs between JDK versions. Compare it with == null or with a known comparator instead.
Only when otherMap's compile-time type is SortedMap or TreeMap. Through a Map-typed variable, the TreeMap(Map) constructor is used and the copy is naturally ordered.
Yes. A clone uses the same comparator object as the original.
No. It is fixed at construction. Create a new TreeMap with the new comparator and putAll the old entries.

Next: compute()

Calculate a new value from the key and its old value.

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

11 people found this page helpful