The Java API specifies the following for the comparing() method in the Comparator<T> interface:
static <T,U extends Comparable<? super U>> Comparator<T> comparing (Function<? super T,? extends U> keyExtractor)
Accepts a function that extracts a Comparable sort key from a type T, and returns a Comparator that compares by that sort key. The returned comparator is serializable if the specified function is also serializable.
For example, to obtain a Comparator that compares Person objects by their last name,
Comparator<Person> byLastName = Comparator.comparing(Person::getLastName);
My question is, what happens when this Comparator's <T>compare(T t1, T t2) method is invoked? For example, suppose persons
is a List<Person> and is sorted using the comparator previously defined above:
Collections.sort(persons, byLastName);
Assuming getLastName
returns a String, which implements Comparable<String>
, how exactly does byLastName
compare the keys extracted by getLastName
? Does the comparator implicitly invoke something like return t1.getLastName().compareTo(t2.getLastName())
?