0

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())?

Nicholas Cousar
  • 205
  • 1
  • 8
  • 1
    How about just look at [how it is implemented in the OpenJDK](https://github.com/AdoptOpenJDK/openjdk-jdk11/blob/master/src/java.base/share/classes/java/util/Comparator.java#L464)? – Sweeper Jul 31 '21 at 04:30
  • Thanks, that did not occur to me. Likewise, it did not occur to me that a functional interface could be used as a return type, and thus a lambda expression could occur in a return statement. It's weird to see because I think of lambdas as anonymous classes that you pass to a method's parameters directly as an argument. – Nicholas Cousar Jul 31 '21 at 05:09

0 Answers0