Difficulty: Intermediate
What is the difference between Comparable and Comparator? How does TreeMap decide ordering and uniqueness of keys?
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.
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.
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.
Comparable, Comparator, TreeMap, Sorting, Red-Black Tree