Composing comparators: method reference works, the lambda equivalent does not.
Samir Talwar
samir at noodlesandwich.com
Sun Jan 5 05:18:02 PST 2014
I don't know about your first question, but I can answer the second.
`comparingInt`, like `IntStream`, exists to prevent boxing and unboxing of
`int` to `Integer`. This can be expensive in certain situations, and Java
is still a language designed to be fast as well as expressive.
I hope the first one gets answered soon. It does look like a regression to
me, though I am no expert.
— Samir.
On 5 Jan 2014 13:05, "Paulo Silveira" <paulo.silveira at caelum.com.br> wrote:
> 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