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
Barbara StreisandOriginal
2024-12-03 21:38:12491browse

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

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

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());

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!

Statement:
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