Composing comparators: method reference works, the lambda equivalent does not.
Paulo Silveira
paulo.silveira at caelum.com.br
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)
.thenComparing(String::length);
This one does not compile:
Comparator<String> c = Comparator.comparing(s -> s.toString())
.thenComparing(s -> s.length());
(compilation error here: https://gist.github.com/peas/8267900)
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 Comparator.compare works just fine to
create a Comparator<Integer>? The only difference I can see is to
avoid NPEs through Integer.compare(...).
Regards
--
Paulo Silveira
www.caelum.com.br
www.casadocodigo.com.br
www.alura.com.br
More information about the lambda-dev
mailing list