Card 02/ 09

ExampleDifficulty: Intermediate1 min

Lambdas Example: Sorting With a Comparator Written on One Line

One call and one lambda, and the pieces the compiler filled in without being told.

A lambda passed to List.sort becomes a Comparator, the interface whose one method, compare, decides the order of two elements. Everything the lambda leaves out, the compiler supplies from that interface. One call:

java
invoices.sort((a, b) -> Long.compare(a.pence(), b.pence()));
What was written, and what the compiler worked out
WrittenInferred
(a, b)Both are Invoice, from List<Invoice>.sort(Comparator<? super Invoice>)
->That this is the body of compare, the only abstract method on Comparator
Long.compare(...)That the int it produces is the return value

Nothing was left out that the compiler could not supply. sort declares its parameter as a Comparator, Comparator has exactly one abstract method, and that method takes two Invoice values and returns an int.

Notice that the lambda has no type written anywhere. Its type came from the place it was passed to, so an identical lambda handed to a method expecting a different interface would become that interface instead.

The standard library also builds comparators for you: Comparator.comparingLong(Invoice::pence) says the same thing by naming the key to sort on, and reads better once the ordering has more than one key.