Full signature of method:
public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T, ? extends U> keyExtractor)
I'm learning lambda expressions and I have this piece of code that compare a List of employees and order them by the name field:
List<Employee> employees = new ArrayList<>();
Collections.sort(employees, Comparator.comparing(Employee::getName));
The code works fine but I have looked at Comparator functional interface in docs and I have found the signature of the method "comparing()".
comparing(Function<? super T,? extends U> keyExtractor)
I don't get the parameter of comparing(). How do I know that the parameter accepts a lambda exprssion? And how is interpreted the constrains: <? super T,? extends U> keyExtractor?
I know that super means that ? has to be type T or above in the hierarchical inheritance, and ? also must be of type U and below in the hierarchical inheritance. But how can we traduce that in my example?
It can be interpreted like this: ? must be of type Employees and above in inheritance chain and the name field must be type Employees or below in inheritance chain? Or ? must be type Array List and above and ? must be type Employees List and below?
?
is not the same as a generic type such asT
and it doesn't mean that both your types of Function has to be in the hierarchy ofEmployee
. They are anything of two different typesT
andU
in simple words, where theT
would be related toEmployee
based on the types of method type inference since it's been called upon aList<Employee>
. – Horatius