Course contentsShow
← Java
Lesson 1359 of 2,87030. Comparable and ComparatorFree lesson

Sorting TreeSet and TreeMap with Comparators

Providing Comparators at construction time to define ordering in sorted collections.

Sorting TreeSet and TreeMap with Comparators

What You'll Learn

You'll learn how to control the ordering of elements in TreeSet and TreeMap by supplying a custom Comparator at construction time.

The Core Idea

Unlike ArrayList or HashMap, TreeSet and TreeMap are sorted collections—they maintain elements in a specific order at all times. By default, they rely on the natural ordering defined by Comparable. However, you can override this behavior by passing a Comparator to their constructors, giving you full control over how elements are sorted.

Think of it like organizing books on a shelf: normally they might be alphabetized by title (natural ordering), but you could instead arrange them by author, publication date, or page count—simply by telling the shelf organizer your preferred sorting rule upfront.

Providing Comparators at Construction Time

When you create a TreeSet or TreeMap, you can pass a Comparator as a constructor argument:

// TreeSet with custom ordering
Comparator<String> lengthComparator = Comparator.comparingInt(String::length);
TreeSet<String> words = new TreeSet<>(lengthComparator);
words.add("elephant");
words.add("cat");
words.add("dog");
// Stored in order: "cat", "dog", "elephant" (by length)

// TreeMap with custom key ordering
Comparator<Integer> reverseOrder = Comparator.reverseOrder();
TreeMap<Integer, String> scores = new TreeMap<>(reverseOrder);
scores.put(85, "Bob");
scores.put(92, "Alice");
scores.put(78, "Charlie");
// Keys sorted descending: 92, 85, 78

Once set, the Comparator governs all insertions and lookups—you can't change it later without creating a new collection.

Why This Matters

This approach lets you use sorted collections with objects that don't implement Comparable, or impose alternative orderings without modifying the class itself.

Key Takeaway: Pass a Comparator to TreeSet or TreeMap constructors to define custom ordering that will govern the collection's entire lifetime—all elements remain sorted according to your specified logic automatically.