Why Comparator.comparing doesn't work with String::toLowerCase method reference?

后端 未结 2 1344
余生分开走
余生分开走 2020-12-19 00:01

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 i

相关标签:
2条回答
  • 2020-12-19 00:50

    I found the solution :

     .sorted((String e) -> e.toLowerCase) 
    

    I think the problem with the syntax

     .sorted(String::toLowerCase)
    

    is that the compiler then expects to pass an Object to the instance method toLowerCase of String. So I need to make my own lambda method, without ignoring the type of the lambda parameter (String), otherwise the compiler still can't resolve it.

    0 讨论(0)
  • 2020-12-19 01:04

    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()));
    
    0 讨论(0)
提交回复
热议问题