Course contentsShow
← Java
Lesson 1134 of 2,87026. Map ImplementationsFree lesson

Creating TreeMaps with Custom Comparators

Using the TreeMap(Comparator) constructor to define custom key ordering independent of Comparable.

Creating TreeMaps with Custom Comparators

You'll learn how to control the sorting order of a TreeMap by providing your own comparison logic at construction time.

What Is a Custom Comparator?

In the previous lesson, you saw TreeMap using natural ordering—keys sorted according to their compareTo method. But what if you want a different order? What if your keys don't implement Comparable at all, or you need multiple different sorting strategies?

That's where the TreeMap(Comparator<? super K> comparator) constructor comes in. You pass a Comparator object that defines exactly how keys should be ordered, completely independent of the key class's Comparable implementation.

How It Works

Think of it like hiring a custom sorter for your library. Instead of following the Dewey Decimal System (natural ordering), you give specific instructions: "Sort by color, then by size." The TreeMap follows your comparator's rules instead of asking the keys themselves how to sort.

// Create a TreeMap that sorts strings by length (shortest first)
TreeMap<String, Integer> lengthMap = new TreeMap<>(
    (s1, s2) -> Integer.compare(s1.length(), s2.length())
);

lengthMap.put("apple", 1);
lengthMap.put("pie", 2);
lengthMap.put("banana", 3);

// Iteration order: "pie" (3), "apple" (5), "banana" (6)

The comparator receives two keys and returns negative if the first is "less than" the second, zero if equal, and positive if greater—just like compareTo, but with your custom logic.

Why This Matters

Custom comparators let you sort by any criteria: reverse alphabetical order, by string length, by a nested field, or any complex business rule. The key class doesn't need to know anything about these sorting strategies.

Key Takeaway: Use the TreeMap(Comparator) constructor to define custom key ordering logic without modifying the key class or relying on its Comparable implementation.