Video in progress

Strong Middle 🌊 Streams and lambdas

sorted() sometimes throws "Comparison method violates its general contract!". What causes it, and how do you write a comparator correctly?

The sorting algorithm (TimSort) throws an IllegalArgumentException if it notices that the comparator returned logically contradictory results. Common causes: overflow when comparing by subtraction, null or a mutable field, and a non-transitive "approximate" comparison. Use Integer.compare, comparingInt and nullsLast.

📖 Answer

The comparator's contract: sgn(compare(a,b)) == -sgn(compare(b,a)), transitivity (if a>b and b>c then a>c), and equal elements stay consistent. If it's violated, the result is either a wrong order or an exception: on a small list almost never, on a large list (more than 32 elements) now and then.

The classic mistake is subtraction:

// int overflow: a = 2_000_000_000, b = -1_000_000_000 -> a negative number comes out
.sorted((a, b) -> a.balance() - b.balance())

A large positive minus a large negative goes past the int limit and flips the sign. The result is a broken order and sometimes an exception.

Other causes:

  • "approximate equality": Math.abs(a - b) < 0.01 ? 0 : ... is not transitive;
  • a field that changes during sorting (a price another thread is updating, a calculation that depends on System.currentTimeMillis());
  • NaN in double fields when compared by hand.

The right way to write it:

.sorted(Comparator.comparingInt(Account::balance))
.sorted(Comparator.comparing(Account::openedAt, Comparator.nullsLast(Comparator.naturalOrder())))
.sorted(Comparator.comparingDouble(Account::rate))   // Double.compare orders NaN correctly too

To verify: write a property-based test (jqwik) for the comparator, or check antisymmetry and transitivity on random data. If this error appears in prod, the first step is to make sure the fields being sorted don't change during the sort: snapshot first (copy into a record), then sort.

You can "turn off" the error with -Djava.util.Arrays.useLegacyMergeSort=true, but that hides the problem: the order will still be wrong.