The 30 second answer
Comparable defines a class's natural order inside the class itself, with one compareTo method, like String sorting alphabetically. Comparator is a separate object that defines any other order, so I can have many: by salary, by name, reversed. Since Java 8 I build them with Comparator.comparing, thenComparing and reversed. TreeMap, TreeSet and sort use whichever I give them, and the order should be consistent with equals.
<!-- level: 1 --> <!-- must_know: true -->
Comparable | Comparator | |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T other) | compare(T a, T b) |
| Where | Inside the class | Outside the class |
| How many | One natural order | As many as you like |
record Emp(String name, int salary) { }
List<Emp> list = new ArrayList<>(List.of(
new Emp("Sara", 900), new Emp("Ali", 1200), new Emp("Reza", 900)));
list.sort(Comparator.comparingInt(Emp::salary).reversed()
.thenComparing(Emp::name));
// [Emp[name=Ali, salary=1200], Emp[name=Reza, salary=900], Emp[name=Sara, salary=900]]compareToandcomparereturn a negative number, zero or a positive number for less than, equal and greater than.- The
ComparableJavadoc strongly recommends that the natural order be consistent withequals, because sorted sets and maps usecompareToinstead ofequalsto decide whether two elements are the same. - Avoid
a - bin a comparator; it can overflow. UseInteger.compareorComparator.comparingInt.
Sources (2)
- Javadoc: java.lang.Comparabledocs.oracle.com
- Javadoc: java.util.Comparatordocs.oracle.com