I would like to understand the definition of the method comparing of Comparator class. I will leave some code in case it helps with the explanation. I'm working with a class called Person that basically stores a name and a last name. This data can be retrieve with get methods.
public class Person {
private final String name;
private final String lastname;
public Person(String name, String lastname) {
this.name = name;
this.lastname = lastname;
}
public String getName() { return name; }
//...
}
I then created a list of Persons:
List<Person> list = Arrays.asList(
new Person("Juan", "García"),
new Person("Ana", "Martínez"),
...
);
I've been testing different ways to sort this list of Persons. Among other possibilities, I found this one:
list.sort(Comparator.comparing(Person::getName));
I understand what these lines do. Basically, this list is sorted using a Comparator that compares using a sort key (a Person's name). Such key is extracted using a reference to the getName method belonging to the Person class.
However, I also like to understand what's going on behind the scenes. My problem is with the comparing method. The Java documentation defines such method like this:
static <T,U extends Comparable<? super U>> Comparator<T> comparing(Function<? super T,? extends U> keyExtractor)
Particularly, I'm struggling with the generic types definition: <T,U extends Comparable<? super U>>; and the definition of the parameter's type: Function<? super T,? extends U>
T represents the comparator type, while U represents the key type, right? So... Why U needs to extends Comparable<? super U>, which in turns uses any superclass of U?
In the argument, the function works with an object belonging to any superclass of T and returns an object belonging to any subclass of U (<? super T,? extends U>), but... why though?
I hope my doubt is clear. Also, sorry for the long explanation.