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);
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
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)));
List vs. Collections Sorting
In List.sort, type inference is performed differently. Consider:
list.sort(Comparator.comparing(String::length).thenComparing(String::compareToIgnoreCase)); // No error
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!