Custom Comparator Implementation
@FunctionalInterface
public interface Comparator<T> {
int compare(T t1, T t2);
static <T> Comparator<T> comparing(
Function<T, Comparable> f){
return (p1, p2) -> f.apply(p1).compareTo(f.apply(p2));
}
default Comparator<T> thenComparing(
Comparator<T> cmp){
return (p1, p2) ->
this.compare(p1, p2) == 0 ?
cmp.compare(p1, p2) : this.compare(p1, p2);
}
default Comparator<T> thenComparing(
Function<T, Comparable> f){
Comparator<T> cmp = comparing(f);
return thenComparing(cmp);
}
}
I created a Person class with three fields, namely firstName, lastName and age, and their respective getters and seters. Using the custom Comparator class, I want to sort an array of faces in the main menu:
Comparator<Person> cmp = Comparator
.comparing(Person::getLastName)
.thenComparing(Person::getFirstName)
.thenComparing(Person::getAge);
Person arr[] = new Person[]{
new Person("Sean", "Gilmore", 22),
new Person("Aaron", "Reidy", 21),
new Person("Jane", "Kennedy", 53),
new Person("Mike", "English", 49)
};
Arrays.sort(arr, cmp);
However, it Arrays.sort(arr, cmp);produces a compilation errorno instance of type variable T exists so that Comparator<Person> conforms to Comparator<? super T>
I am throwing away this error and I would like to know how to sort the Person array using cmpComparator.