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:
Store the intermediate Comparator in a variable:
Comparator<String> comparator = Comparator.comparing(String::toLowerCase);
System.out.println(
Arrays.stream(stringsArray)
.sorted(comparator.reversed())
.collect(Collectors.toList()));
Use String.CASE_INSENSITIVE_ORDER
:
System.out.println(
Arrays.stream(stringsArray)
.sorted(String.CASE_INSENSITIVE_ORDER.reversed())
.collect(Collectors.toList()));
Add explicit type parameters:
System.out.println(
Arrays.stream(stringsArray)
.sorted(Comparator.<String,String>comparing(String::toLowerCase).reversed())
.collect(Collectors.toList()));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…