Home > Java > javaTutorial > Why Does `Comparator.comparing().reversed()` Cause a Compiler Error with Lambdas?

Why Does `Comparator.comparing().reversed()` Cause a Compiler Error with Lambdas?

Susan Sarandon
Release: 2024-12-20 17:22:10
Original
259 people have browsed it

Why Does `Comparator.comparing().reversed()` Cause a Compiler Error with Lambdas?

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());
Copy after login

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());
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template