Understanding the Compiler Error in Comparator.reversed() with Lambdas
When attempting to sort a list of User objects using a lambda expression for the Comparator, such as:
List<User> userList = Arrays.asList(u1, u2, u3); userList.sort(Comparator.comparing(u -> u.getName()).reversed());
the compiler may display an error stating that it cannot find the getName() method in the lambda's u variable. This issue stems from a weakness in the compiler's type inference mechanism.
To resolve this error, we need to establish the target type for the lambda. When sorting using Comparator.comparing(), the lambda must take an argument of the same type as the objects in the list.
In the first line of the code, where we use a method reference, the target type is inferred from the method parameter type, which is User. This allows the compiler to correctly infer the type of u within the lambda.
However, in the third line, where we use a lambda expression instead of a method reference, the call to reversed() disrupts the target type inference. The compiler cannot propagate the target type back to the receiver, leaving u with an inferred type of Object, which does not have a getName() method.
To resolve this issue, we can either use a method reference or explicitly specify the type of u in the lambda, like so:
userList.sort(Comparator.comparing((User u) -> u.getName()).reversed());
This ensures that the compiler can infer the correct type for u within the lambda and successfully sort the list according to the specified comparator.
The above is the detailed content of Why Does `Comparator.comparing().reversed()` Cause a Compiler Error with Lambdas?. For more information, please follow other related articles on the PHP Chinese website!