I have this code that I try to convert the method reference ("String::length") into equivalent lambda expression.
Stream<String> s = Stream.of("hello", "your name", "welcome", "z");
List<String> list = s.sorted((a, b) -> Comparator.comparingInt(String::length).compare(a, b)).collect(toList());
// List<String> list = s.sorted((a, b) -> Comparator.comparingInt( p -> {return ((String)p).length();}).compare(a, b)).collect(toList());
The only way it works is outlined in the commented line. I need to cast the argument "p".
Seems like at compile time it specifies the type of the argument "p" to be an Object if I use the lambda expression and I need to cast explicitly. See below:
<Object> Comparator<Object> java.util.Comparator.comparingInt(ToIntFunction<? super Object> keyExtractor)
When I use a String::length method reference then at compile time the implicit argument is correctly understood as a String instance. What is so special in this case? See below.
<String> Comparator<String> java.util.Comparator.comparingInt(ToIntFunction<? super String> keyExtractor)