javasortinglambdacompiler-errorsreverse

Java - compilation error when reverse order


why the second sort occurs compilation error?

List<List<Long>> list = Lists.newArrayList();
list.stream().sorted(Comparator.comparing(x -> x.get(0))); //works fine
list.stream().sorted(Comparator.comparing(x -> x.get(0)).reversed()); //cannot work
list.stream().sorted(Collections.reverseOrder(Comparator.comparing(x -> x.get(0)))); //works fine too

I read the IDE prompt but I cannot understand. Can somebody explains it in an easy way to understand?


Solution

  • The compiler needs help with the type inference in this case for some reason. Either specify the lambda parameter type:

    list.stream().sorted(Comparator.comparing((List<Long> x) -> x.get(0)).reversed());
    

    or save the comparator in a variable:

    Comparator<List<Long>> comparing = Comparator.comparing(x -> x.get(0));
    list.stream().sorted(comparing.reversed());
    

    or specify what type of comparator you want:

    list.stream().sorted(Comparator.<List<Long>, Long>comparing(x -> x.get(0)).reversed());
    

    That should give the compiler enough to figure it out.

    Generics sometimes are weird about this and you need to specify the concrete typing. Maybe this gets improved at some point, but right now this is all you can do.