为什么Comparator.comparing不能与String :: toLowerCase方法引用一起使用? [英] Why Comparator.comparing doesn't work with String::toLowerCase method reference?
问题描述
我试图按逆序(忽略大小写)排序一个字符串数组,而不修改它,只打印它。所以我使用的是Java8流。但我无法做到。
I am trying to sort an array of Strings by reverse order (ignoring case), without modifying it, and just printing it. So I am using Java8 stream. But I can't manage to do it.
这是我的尝试:
package experimentations.chapter02;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.Collectors;
public class StringStream {
public static void main(String[] args) {
sortStrings();
}
public static void sortStrings(){
String[] stringsArray = "The quick brown fox has a dirty ladder".split("\\s+");
System.out.println(
Arrays.stream(stringsArray)
.sorted(Comparator.comparing(String::toLowerCase).reversed())
.collect(Collectors.toList())
);
}
}
这里的问题是<$静态方法 Comparator.comparing
中不接受c $ c> String :: toLowerCase 。
The problem here is that String::toLowerCase
is not accepted in the static method Comparator.comparing
.
与此同时,我设法对数组进行排序,但修改:
Meanwhile, I managed to sort the array, but modifying it:
public static void sortStrings(){
String[] stringsArray = "The quick brown fox has a dirty ladder".split("\\s+");
System.out.println(
Arrays.stream(stringsArray)
.map(String::toLowerCase)
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList())
);
}
那么,最简单的解决方法是什么?
So, what is the simpliest workaround?
推荐答案
问题是,Java无法推断出某些复杂表达式的泛型类型。第一个语句有效,而第二个语句导致编译时错误:
The problem is, that Java can not deduce the generic types for some complex expressions. The first statement works, whereas the second statement leads to a compile-time error:
Comparator<String> comparator = Comparator.comparing(String::toLowerCase);
Comparator<String> comparator = Comparator.comparing(String::toLowerCase).reversed();
有几种方法可以解决这个问题。以下是其中三个:
There are several ways to solve the problem. Here are three of them:
将中间比较器存储在变量中:
Comparator<String> comparator = Comparator.comparing(String::toLowerCase);
System.out.println(
Arrays.stream(stringsArray)
.sorted(comparator.reversed())
.collect(Collectors.toList()));
使用 String.CASE_INSENSITIVE_ORDER
:
System.out.println(
Arrays.stream(stringsArray)
.sorted(String.CASE_INSENSITIVE_ORDER.reversed())
.collect(Collectors.toList()));
添加显式类型参数:
System.out.println(
Arrays.stream(stringsArray)
.sorted(Comparator.<String,String>comparing(String::toLowerCase).reversed())
.collect(Collectors.toList()));
这篇关于为什么Comparator.comparing不能与String :: toLowerCase方法引用一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!