# Comparable vs Comparator and How TreeMap Sorts

> What is the difference between Comparable and Comparator? How does TreeMap decide ordering and uniqueness of keys?

Canonical: https://www.internhack.in/learn/interview/java-interview/java-comparable-comparator-treemap
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What is the difference between Comparable and Comparator? How does TreeMap decide ordering and uniqueness of keys?

## Answer

Sorting custom objects is something you will do in almost every coding round, so let's make the distinction between Comparable and Comparator crisp. The whole thing comes down to one question: who owns the definition of order, the class itself or someone outside it?

Comparable lives in java.lang and has one method: int compareTo(T other). When a class implements Comparable, it declares its natural ordering, the default way instances are compared. Strings are ordered alphabetically, Integers numerically, LocalDate chronologically. You get exactly one natural ordering per class because a class can implement compareTo only once. Collections.sort(list) and Arrays.sort(array) without a comparator use it.

Comparator lives in java.util and has one abstract method: int compare(T a, T b). It is defined outside the class, so you can create as many orderings as you like: sort students by marks, then by name, then by age descending. This is the tool you use when you cannot modify the class (a library type), when you need multiple orderings, or when you want a different order from the natural one.

The return contract for both is: negative if the first is smaller, zero if equal, positive if larger. A famous bug is writing return a.x - b.x for ints. It can overflow when values have opposite signs and huge magnitudes, giving the wrong sign. Use Integer.compare(a.x, b.x) instead.

Java 8 made Comparator much nicer with static and default methods: Comparator.comparing(keyExtractor), comparingInt, thenComparing to chain, reversed to flip, naturalOrder, reverseOrder, and nullsFirst and nullsLast to handle nulls. Sorting by marks descending and then by name reads almost like English.

Now TreeMap. It is a red-black tree (a self-balancing binary search tree), so get, put and remove are O(log n), and keys are always kept in sorted order. It implements NavigableMap, giving methods such as firstKey, lastKey, floorKey, ceilingKey, higherKey, lowerKey, headMap, tailMap and subMap, great for range queries and problems like finding the nearest smaller value.

TreeMap decides everything using the comparison, not equals or hashCode. If you pass a Comparator to the constructor, it is used; otherwise the keys must implement Comparable, or you get a ClassCastException at the first put. Two keys are considered the same when compare returns 0. That is a huge point: if your comparator returns 0 for objects that are not equal, TreeMap treats them as duplicates and the second put just overwrites the value. The same applies to TreeSet. Ideally the ordering should be consistent with equals; otherwise the collection violates the Map interface's general contract.

TreeMap does not allow null keys with natural ordering, since compareTo on null throws NullPointerException, though values can be null. Iteration returns keys in ascending order.

When would you choose TreeMap over HashMap? When you need sorted iteration or range and nearest-neighbour queries. If not, HashMap is faster at O(1) average.

A frequent coding round variant: sort a list of employees by salary descending and break ties by name. Write it with Comparator chaining rather than an if-else inside a compare method; it is shorter and less error-prone.

## Code examples

### Chained comparator

```
import java.util.*;

public class SortDemo {
    record Student(String name, int marks) {}

    public static void main(String[] args) {
        List<Student> list = new ArrayList<>(List.of(
            new Student("Asha", 90),
            new Student("Ravi", 85),
            new Student("Neha", 90),
            new Student("Karan", 85)));

        list.sort(Comparator.comparingInt(Student::marks).reversed()
                            .thenComparing(Student::name));

        for (Student s : list) {
            System.out.println(s.name() + " " + s.marks());
        }
    }
}
```

Sorted by marks descending first, and ties are broken by name ascending.

### TreeMap uniqueness comes from the comparator

```
import java.util.*;

public class TreeMapDemo {
    public static void main(String[] args) {
        TreeMap<String, Integer> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        map.put("b", 1);
        map.put("A", 2);
        map.put("B", 3);
        System.out.println(map);
        System.out.println(map.firstKey() + " " + map.ceilingKey("aa"));
    }
}
```

B is treated as the same key as b, so the value is replaced but the original key b stays. ceilingKey returns the smallest key greater than or equal to aa, which is b.

## Key points

- Comparable defines natural order inside the class; Comparator defines external, multiple orderings.
- Use Integer.compare, not subtraction, to avoid overflow.
- TreeMap is a red-black tree with O(log n) operations and sorted keys.
- TreeMap and TreeSet use compare or compareTo for uniqueness, not equals.
- Comparator.comparing, thenComparing and reversed make chained sorting readable.

## Common follow-up questions

- Can a TreeMap have a null key?
- What happens if a class is used in a TreeSet without implementing Comparable?
- What is the difference between HashMap and TreeMap performance?
- How do you sort a Map by its values?

## Interview tips

- Mention the subtraction overflow bug. It signals real experience.
- Explain that TreeMap uses compare for equality; it often surprises candidates.

## Concepts covered

Comparable, Comparator, TreeMap, Sorting, Red-Black Tree

Previous: [How HashSet Works Internally](https://www.internhack.in/learn/interview/java-interview/java-hashset-internals) · Next: [Fail-Fast vs Fail-Safe Iterators](https://www.internhack.in/learn/interview/java-interview/java-fail-fast-vs-fail-safe) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [Generics, Wildcards and Type Erasure](https://www.internhack.in/learn/interview/java-interview/java-generics-type-erasure)
- [JVM Memory: Heap, Stack, Metaspace](https://www.internhack.in/learn/interview/java-interview/java-jvm-memory-model)
- [Garbage Collection Basics and GC Roots](https://www.internhack.in/learn/interview/java-interview/java-garbage-collection-basics)
- [Thread vs Runnable and the Thread Lifecycle](https://www.internhack.in/learn/interview/java-interview/java-thread-vs-runnable)
- [synchronized vs volatile: Visibility, Atomicity and Ordering](https://www.internhack.in/learn/interview/java-interview/java-synchronized-volatile)
- [wait(), notify() and the Producer-Consumer Pattern](https://www.internhack.in/learn/interview/java-interview/java-wait-notify)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
