Composing comparators: method reference works, the lambda equivalent does not.

Paulo Silveira paulo.silveira at
Sun Jan 5 05:01:57 PST 2014

While trying to compose comparators, I am having strange problems
using lambdas instead of method references.

This one compiles (I know the resulting comparator does not make sense):

Comparator<String> c = Comparator.comparing(String::toString)

This one does not compile:

Comparator<String> c = Comparator.comparing(s -> s.toString())
                              .thenComparing(s -> s.length());

(compilation error here:

It seems the compiler is expecting a Function<Object, String> instead
of Function<String, String>. The latest Goetz' state of lambda says
this should work, but it gives me the same compilation error:

Comparator<Person> c = Comparator.comparing(p -> p.getLastName())
                                 .thenComparing(p -> p.getFirstName());

My build is 1.8.0-ea-b121

Another quick question: when would I need to use
Comparator.comparingInt if works just fine to
create a Comparator<Integer>? The only difference I can see is to
avoid NPEs through

Paulo Silveira

More information about the lambda-dev mailing list