comparing and thenComparing gives compile error

前端 未结 1 673
春和景丽
春和景丽 2020-12-03 17:57

I am trying to sort List of employees by name then age using Java8 Comparator, I have created below Comparator but it gives me a compi

相关标签:
1条回答
  • 2020-12-03 18:31

    Java needs to know a type of all variables. In many lambdas it can infer a type, but in your first code snippet, it cannot guess the type of s. I think the standard way to solve that problem would be to declare it explicitly:

        Comparator<String> c = Comparator.comparing((String s) -> s.split("\\s+")[0])
                .thenComparingInt(s -> Integer.parseInt(s.split("\\s+")[1]));
    

    If you look at this answer, it has a similar type declaration in the argument to Comparator.comparing().

    Your method, explicitly giving the type arguments of comparing(), obviously works too.

    For your other method, declaring two comparators, I am pretty confident that in this case Java can infer from the String on the left side of the assignment, just as in the conventional List <String> = new ArrayList<>();. When you go on to call thenComparing() in the same expression, Java can no longer see that the type from the left side is relevant. It would be a bit like int size = new ArrayList<>().size(); This works too:

        Comparator<String> name = Comparator.comparing(s -> s.split("\\s+")[0]);
        Comparator<String> c = name.thenComparingInt(s -> Integer.parseInt(s.split("\\s+")[1]));
    
    0 讨论(0)
提交回复
热议问题