Home > Java > javaTutorial > Why Does `Comparator.reversed()` Fail with Lambda Expressions in Java Sorting?

Why Does `Comparator.reversed()` Fail with Lambda Expressions in Java Sorting?

Barbara Streisand
Release: 2024-12-03 21:38:12
Original
570 people have browsed it

Why Does `Comparator.reversed()` Fail with Lambda Expressions in Java Sorting?

Why Comparator.reversed() Fails with Lambdas

When sorting a list of User objects using Comparator.comparing with a lambda expression, an error may occur:

userList.sort(Comparator.comparing(u -> u.getName()).reversed()); // Compiler error
Copy after login

This is due to a limitation in the compiler's type inference mechanism. The compiler struggles to determine the type of the lambda argument 'u'.

In the following example, using a method reference allows the compiler to infer the target type and avoid the error:

userList.sort(Comparator.comparing(User::getName).reversed()); // works
Copy after login

The method reference provides additional type information, which the compiler uses to infer the type of 'u' as User.

To avoid the error when using a lambda, you can explicitly specify the type of the lambda argument:

userList.sort(Comparator.comparing((User u) -> u.getName()).reversed());
Copy after login

In future compiler releases, this issue may be addressed and the error may no longer occur.

The above is the detailed content of Why Does `Comparator.reversed()` Fail with Lambda Expressions in Java Sorting?. 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