I am trying to sort an Array of Strings based on their lengths using Comparator.comparing function. So, I have the following piece of code:
String[] arr = new String[]{"Hello","I","Am","Learning","Java"};
- When I try to sort it in decreasing order of their lengths, I get the results as expected using Method reference but it gives a Compile Time Error (CTE) using lambda i.e.,
Cannot resolve method length()
:
Arrays.sort(arr, Comparator.comparing(String::length).reversed()); //Using method reference Arrays.sort(arr, Comparator.comparing(s->s.length()).reversed()); //Using Lambda CTE
- But when I sort it in increasing order of their lengths, they both yield expected results:
Arrays.sort(arr, Comparator.comparing(String::length)); //Using method reference Arrays.sort(arr, Comparator.comparing(s->s.length())); //Using Lambda
So, why does IntelliJ throws CTE in first scenario using lambdas, when method reference can replace lambdas in scenarios involving single method invocation, so they should ideally behave the same?
Also, why the CTE described above needs to be replaced by
Comparator.comparing((String s) -> s.length()).reversed()