Home > Java > javaTutorial > Why Does Java 8 Comparator Type Inference Fail When Chaining `thenComparing` Calls?

Why Does Java 8 Comparator Type Inference Fail When Chaining `thenComparing` Calls?

Susan Sarandon
Release: 2024-11-28 12:53:11
Original
414 people have browsed it

Why Does Java 8 Comparator Type Inference Fail When Chaining `thenComparing` Calls?

Java 8 Comparator Type Inference Confusion

Java 8 introduced improvements to Comparator usage through lambda expressions. However, when chaining multiple thenComparing calls, type inference can become unclear. This issue stems from the fact that lambda expressions lack type inference as method receiver expressions.

Comparator Chaining and Type Inference

Consider the following code:

Comparator<String> c1 = Comparator.comparing(String::length);
Comparator<String> c2 = c1.thenComparing(String::compareToIgnoreCase);
Copy after login

The first line uses a method reference without type parameters, which triggers type inference based on the return type of String::length. This type is used to infer the type of p1 in the thenComparing method.

However, in a situation like this:

Collections.sort(list, c1.thenComparing(String::compareToIgnoreCase)); // Error: cannot resolve method
Copy after login

Type inference fails because the Collections.sort method lacks specific type information for c1. To resolve this issue, we can provide explicit type parameters:

Collections.sort(list, c1.thenComparing(Comparator.comparing(String::compareToIgnoreCase)));
Copy after login

List vs. Collections Sorting

In List.sort, type inference is performed differently. Consider:

list.sort(Comparator.comparing(String::length).thenComparing(String::compareToIgnoreCase)); // No error
Copy after login

Here, type inference is not required because the Comparator is created directly within the sort method, providing the necessary type information. However, this only holds for the first thenComparing call. Subsequent calls without explicit type parameters will result in errors.

Eclipse-Specific Errors

It's important to note that the errors you encountered may have been Eclipse-specific. Compiling the code with the JDK 8 javac compiler often resolves these issues.

The above is the detailed content of Why Does Java 8 Comparator Type Inference Fail When Chaining `thenComparing` Calls?. 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