Comparable and Comparator
Java sorts objects through two interfaces: Comparable gives a class its one natural order, and Comparator describes any other order from outside the class. This page explains the contract both must follow, builds orders with the Comparator factory methods, handles nulls, shows the bugs that break sorting and sorted collections, and measures what boxing in comparators costs.
Contents
Two interfaces for ordering
Sorting algorithms and sorted collections never look at fields themselves. They only ask one question about two objects: which comes first? That question is answered by an int
(Java 1.2) is implemented by a class to define its natural order withComparable<T> .compareTo(T other) , the number wrappers,String andLocalDate all have one.BigDecimal ,Collections.sort(list) andTreeSet use it when no comparator is given.TreeMap (Java 1.2) is a separate object withComparator<T> . A class can have any number of comparators, and they can be written for classes you cannot change. Since Java 8 it has factory and combinator methods such ascompare(a, b) ,comparing ,thenComparing andreversed .nullsFirst
Both must follow the same contract: the sign must flip when the arguments are swapped, the order must be transitive (if a < b and b < c then a < c), and elements that compare as 0 must compare the same way with everything else. The contract also recommends, but does not require, that compareToequals
| Method | Since | Best for |
|---|---|---|
Comparator.comparing(keyExtractor) | Java 8 | Ordering by one property |
comparingIntcomparingLongcomparingDouble | Java 8 | Primitive keys, without boxing |
thenComparing(...) | Java 8 | Tie-breakers |
reversed()Comparator.reverseOrder() | Java 8 | Descending order |
nullsFirstnullsLast | Java 8 | Lists that contain null |
Integer.compareLong.compare | Java 7 | Writing compareTo |
String.CASE_INSENSITIVE_ORDERCollator | Java 1.2, 1.1 | Text; see |
Every program on this page was run on JDK 21.
Comparable: a natural order for your own class
Version numbers are a good example, because their natural order is not the order of their text: 2.10 comes after 2.9, and 10.0 after both.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class NaturalOrder {
// A class opts in to a natural order by implementing Comparable
record Version(int major, int minor) implements Comparable<Version> {
@Override
public int compareTo(Version other) {
int byMajor = Integer.compare(major, other.major);
return byMajor != 0 ? byMajor : Integer.compare(minor, other.minor);
}
@Override
public String toString() {
return major + "." + minor;
}
}
public static void main(String[] args) {
List<Version> versions = new ArrayList<>(List.of(
new Version(2, 10), new Version(1, 4), new Version(2, 9), new Version(10, 0)));
Collections.sort(versions);
System.out.println("sorted: " + versions);
// Strings sort by character code, which is why "10.0" text would come before "2.9"
List<String> asText = new ArrayList<>(List.of("2.10", "1.4", "2.9", "10.0"));
Collections.sort(asText);
System.out.println("as text: " + asText);
System.out.println("compare 1.4 to 2.9: " + new Version(1, 4).compareTo(new Version(2, 9)));
System.out.println("max: " + Collections.max(versions));
}
}
Output:
sorted: [1.4, 2.9, 2.10, 10.0]
as text: [1.4, 10.0, 2.10, 2.9]
compare 1.4 to 2.9: -1
max: 10.0
compares the major numbers first and only looks at the minor numbers on a tie, the pattern for any multi-part key.compareTo returns -1, 0 or 1 safely for any two values. Subtraction can overflow, as a later section shows.Integer.compare- Sorting the same versions as strings gives
, because strings compare character by character and1.4, 10.0, 2.10, 2.9 comes before'1' .'2' - Once a class is
,Comparable ,Collections.max and streams'TreeSet all use its order without extra code.sorted()
The generic parameter matters: implementing Comparable<Version>ComparableequalsComparator
Building comparators with comparing and thenComparing
The employee list has ties in both department and salary, so each step of the chain decides some of the order.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class ComparatorChains {
record Employee(String name, String dept, int salary) {
}
public static void main(String[] args) {
List<Employee> staff = new ArrayList<>(List.of(
new Employee("Priya", "Eng", 120),
new Employee("Arjun", "Ops", 90),
new Employee("Mei", "Eng", 150),
new Employee("Tom", "Ops", 90),
new Employee("Ana", "Eng", 120)));
// Department A-Z, then salary high to low, then name A-Z
Comparator<Employee> order = Comparator
.comparing(Employee::dept)
.thenComparing(Employee::salary, Comparator.reverseOrder())
.thenComparing(Employee::name);
staff.sort(order);
staff.forEach(e -> System.out.println(e.dept() + " " + e.salary() + " " + e.name()));
// comparingInt avoids boxing each salary into an Integer
Comparator<Employee> bySalary = Comparator.comparingInt(Employee::salary);
System.out.println("lowest paid: " + staff.stream().min(bySalary).orElseThrow().name());
// reversed() flips the WHOLE chain built so far
staff.sort(order.reversed());
System.out.println("fully reversed first: " + staff.get(0).name());
}
}
Output:
Eng 150 Mei
Eng 120 Ana
Eng 120 Priya
Ops 90 Arjun
Ops 90 Tom
lowest paid: Arjun
fully reversed first: Tom
- The chain reads like the requirement: department A to Z, then salary from high to low, then name.
andAna both earn 120 in Eng, so the name decides.Priya reverses only that step.thenComparing(key, Comparator.reverseOrder()) takes ancomparingInt key directly;int would box each salary into ancomparing for every comparison.Integer applies to the whole chain built so far, not just the last step, so the fully reversed order starts with Ops andreversed() . PutTom inside a step when only that step should be descending.reversed()
Nulls, overflow and duplicates in sorted sets
Four small cases cover the mistakes that show up most often in code reviews: a list with nulls, a subtraction comparator, a comparator that treats different elements as equal, and mixed-case text.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
public class NullsAndPitfalls {
public static void main(String[] args) {
// 1. nullsFirst / nullsLast wrap a comparator so null elements do not throw
List<String> cities = new ArrayList<>(Arrays.asList("Pune", null, "Austin", null, "Oslo"));
cities.sort(Comparator.nullsLast(Comparator.naturalOrder()));
System.out.println("nullsLast: " + cities);
// 2. Subtraction as a comparator overflows for large values
Comparator<Integer> bySubtraction = (a, b) -> a - b;
int wrong = bySubtraction.compare(Integer.MIN_VALUE, 1);
int right = Integer.compare(Integer.MIN_VALUE, 1);
System.out.println("MIN_VALUE vs 1, subtraction: " + wrong + " Integer.compare: " + right);
// 3. A TreeSet treats compare() == 0 as "same element" and drops it
Comparator<String> byLength = Comparator.comparingInt(String::length);
TreeSet<String> set = new TreeSet<>(byLength);
set.addAll(List.of("kiwi", "pear", "fig", "plum"));
System.out.println("TreeSet by length: " + set);
// Adding a tie-breaker keeps every distinct element
TreeSet<String> fixed = new TreeSet<>(byLength.thenComparing(Comparator.naturalOrder()));
fixed.addAll(List.of("kiwi", "pear", "fig", "plum"));
System.out.println("with tie-breaker: " + fixed);
// 4. Case-insensitive order for text
List<String> names = new ArrayList<>(List.of("bob", "Alice", "carol", "Bob"));
names.sort(String.CASE_INSENSITIVE_ORDER);
System.out.println("case-insensitive: " + names);
}
}
Output:
nullsLast: [Austin, Oslo, Pune, null, null]
MIN_VALUE vs 1, subtraction: 2147483647 Integer.compare: -1
TreeSet by length: [fig, kiwi]
with tie-breaker: [fig, kiwi, pear, plum]
case-insensitive: [Alice, bob, Bob, carol]
- Natural order throws
on a null element.NullPointerException puts the nulls at the end and sorts the rest normally.nullsLast(naturalOrder()) looks like a compact comparator, but(a, b) -> a - b overflows to 2,147,483,647, so the smallest value is reported as larger than 1. Always useInteger.MIN_VALUE - 1 orInteger.compare .comparingInt- A
uses the comparator, notTreeSet , to decide whether an element is already present. Ordered by length only,equals andpear were dropped because they have the same length asplum . A tie-breaker keeps all four.kiwi sortsString.CASE_INSENSITIVE_ORDER andbob together; between them the original order is kept, because sorting is stable.Bob
When the contract is broken
A comparator that breaks the contract does not always fail loudly. The program shows four ways it goes wrong, from a set that holds fewer elements than expected to a sort that throws.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
public class ContractBreaks {
public static void main(String[] args) {
// compareTo inconsistent with equals: BigDecimal 2.0 and 2.00
List<BigDecimal> amounts = List.of(new BigDecimal("2.0"), new BigDecimal("2.00"));
Set<BigDecimal> hash = new HashSet<>(amounts);
Set<BigDecimal> tree = new TreeSet<>(amounts);
System.out.println("HashSet size " + hash.size() + ", TreeSet size " + tree.size()
+ ", equals: " + amounts.get(0).equals(amounts.get(1))
+ ", compareTo: " + amounts.get(0).compareTo(amounts.get(1)));
// A comparator that never returns 0 and is not antisymmetric
Comparator<Integer> neverEqual = (a, b) -> a < b ? -1 : 1;
System.out.println("neverEqual.compare(5, 5) = " + neverEqual.compare(5, 5)
+ " (should be 0)");
// A comparator that breaks transitivity: TimSort may detect it and throw
Random random = new Random(42);
List<Integer> data = new ArrayList<>();
for (int i = 0; i < 2000; i++) {
data.add(random.nextInt(100));
}
Comparator<Integer> broken = (a, b) -> Math.abs(a - b) < 10 ? 0 : Integer.compare(a, b);
try {
Collections.sort(data, broken);
System.out.println("broken comparator: sorted without an error, order is unreliable");
} catch (IllegalArgumentException e) {
System.out.println("broken comparator: " + e.getMessage());
}
// Comparing mutable fields: changing an element after insertion corrupts a TreeSet
List<int[]> boxes = new ArrayList<>();
TreeSet<int[]> byFirst = new TreeSet<>(Comparator.comparingInt(a -> a[0]));
for (int i : new int[] {5, 1, 9}) {
int[] box = {i};
boxes.add(box);
byFirst.add(box);
}
boxes.get(0)[0] = 20; // the element that was 5 is now 20
System.out.println("contains the changed element? " + byFirst.contains(boxes.get(0))
+ ", first=" + byFirst.first()[0] + ", last=" + byFirst.last()[0]);
}
}
Output:
HashSet size 2, TreeSet size 1, equals: false, compareTo: 0
neverEqual.compare(5, 5) = 1 (should be 0)
broken comparator: Comparison method violates its general contract!
contains the changed element? true, first=1, last=9
's natural order is inconsistent with equals:BigDecimal and2.0 compare as 0 but are not2.00 , so aequals keeps both and aHashSet keeps one. TheTreeSetBigDecimal page explains why.- A comparator that never returns 0 says that 5 comes after 5, which breaks the sign rule and makes
andcontains on sorted collections unreliable.remove - The "within 10 counts as equal" comparator is not transitive: 0 equals 9 and 9 equals 18, but 0 is less than 18. On 2,000 elements,
, which uses TimSort, detected the inconsistency and threwCollections.sort with "Comparison method violates its general contract!". On other data it may finish silently with a wrong order.IllegalArgumentException - A sorted collection places each element when it is added. Changing the field the comparator reads afterwards leaves the element in the wrong place: the set holds 20 but
reports 9. Compare only on fields that do not change while the element is in the collection.last()
Where comparators are used
The same comparator object works everywhere Java needs an order: stream operations, collectors, priority queues and sorted maps. The tasks have duplicate priorities, so the tie-breaker matters in each case.
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.StringJoiner;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class WhereUsed {
record Task(String name, int priority) {
}
public static void main(String[] args) {
List<Task> tasks = List.of(new Task("deploy", 2), new Task("fix bug", 1),
new Task("write docs", 3), new Task("review", 1));
Comparator<Task> byPriority = Comparator.comparingInt(Task::priority)
.thenComparing(Task::name);
// Streams
System.out.println("sorted: "
+ tasks.stream().sorted(byPriority).map(Task::name).toList());
System.out.println("max: " + tasks.stream().max(byPriority).orElseThrow().name());
Map<Integer, String> firstPerPriority = tasks.stream().collect(Collectors.groupingBy(
Task::priority, TreeMap::new, Collectors.collectingAndThen(
Collectors.minBy(Comparator.comparing(Task::name)), t -> t.orElseThrow().name())));
System.out.println("minBy name per priority: " + firstPerPriority);
// A priority queue always hands out the smallest element first
PriorityQueue<Task> queue = new PriorityQueue<>(byPriority);
queue.addAll(tasks);
StringJoiner order = new StringJoiner(" | ");
while (!queue.isEmpty()) {
order.add(queue.poll().name());
}
System.out.println("PriorityQueue: " + order);
// A sorted map keyed by a comparator
TreeMap<String, Integer> byLengthThenText = new TreeMap<>(
Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
for (Task t : tasks) {
byLengthThenText.put(t.name(), t.priority());
}
System.out.println("TreeMap: " + byLengthThenText);
// Comparator.naturalOrder and reverseOrder for Comparable types
System.out.println("max string: " + List.of("pear", "apple", "fig").stream()
.max(Comparator.naturalOrder()).orElseThrow());
}
}
Output:
sorted: [fix bug, review, deploy, write docs]
max: write docs
minBy name per priority: {1=fix bug, 2=deploy, 3=write docs}
PriorityQueue: fix bug | review | deploy | write docs
TreeMap: {deploy=2, review=1, fix bug=1, write docs=3}
max string: pear
,sorted(cmp) andmax(cmp) on streams take a comparator directly. With the tie-breaker,min(cmp) comes beforefix bug , both priority 1.review andCollectors.minBy find the extreme element within each group of amaxBy ; see thegroupingBygroupingBy page .- A
built with the comparator always returns the smallest remaining element fromPriorityQueue , which is how task schedulers work. Its iteration order is not sorted; onlypoll() is. ThepollPriorityQueue page explains the heap behind it. - A
keeps its keys in comparator order, here shortest name first, with alphabetical order breaking ties.TreeMap turns aComparator.naturalOrder() type's own order into a comparator, for APIs that require one.Comparable
What comparators cost
A sort calls the comparator millions of times, so small overheads multiply. The program sorts 500,000 orders with four comparators, each on a fresh copy, keeping the fastest of three runs.
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
public class ComparatorSpeed {
record Order(String customer, int amount, long id) {
}
public static void main(String[] args) {
Random random = new Random(9);
List<Order> orders = new ArrayList<>();
for (int i = 0; i < 500000; i++) {
orders.add(new Order("c" + random.nextInt(1000), random.nextInt(10000), i));
}
System.out.printf("sort %,d orders%n", orders.size());
time("comparing(Order::amount) (boxes)", orders, Comparator.comparing(Order::amount));
time("comparingInt(Order::amount)", orders, Comparator.comparingInt(Order::amount));
time("lambda Integer.compare", orders, (a, b) -> Integer.compare(a.amount(), b.amount()));
time("customer, then amount", orders, Comparator.comparing(Order::customer)
.thenComparingInt(Order::amount));
}
// Best of 3 runs, each on a fresh copy of the unsorted list
static void time(String name, List<Order> input, Comparator<Order> cmp) {
long best = Long.MAX_VALUE;
for (int run = 0; run < 3; run++) {
List<Order> copy = new ArrayList<>(input);
long t0 = System.nanoTime();
copy.sort(cmp);
best = Math.min(best, System.nanoTime() - t0);
}
System.out.printf(" %-34s %6.1f ms%n", name, best / 1e6);
}
}
Output (2-CPU Linux machine, JDK 21; differences of a few milliseconds are noise):
sort 500,000 orders
comparing(Order::amount) (boxes) 185.1 ms
comparingInt(Order::amount) 155.1 ms
lambda Integer.compare 153.4 ms
customer, then amount 298.9 ms
boxes thecomparing(Order::amount) keys intoint objects and was the slowest of the single-key versions.Integer and a hand-written lambda avoid boxing; the JIT often removes much of the boxing anyway, so the gap is modest.comparingInt- A two-step chain that compares strings first took longer, because string comparison is more work and most comparisons are decided by the customer name.
The differences are small next to the cost of a wrong comparator. Choose the clearest comparator, and prefer comparingInt
Which to use
| Situation | Use |
|---|---|
| The class has one obvious order | Implement Comparable |
| Any other order, or a class you cannot change | A Comparator |
| Order by a property | Comparator.comparing(Type::getter) |
| Primitive key | comparingIntcomparingLongcomparingDouble |
| Tie-breakers | thenComparing |
| Descending | reversed()reverseOrder() |
| Nulls in the data | nullsFirstnullsLast |
Writing compareTo | Integer.compare |
Keys in a TreeSetTreeMap | A comparator consistent with equals |
For sorting lists, arrays and streams with these comparators, see