Custom implementation of Comparator
@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 have created a Person class with three fields, namely the firstName, lastName and age, and their respective getters and setters. Using the custom Comparator class I want to sort an array of persons in main as under:
Comparator<Person> cmp = Comparator
.comparing(Person::getLastName) // Extract Property and compare
.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 Arrays.sort(arr, cmp); throws a compile error no instance of type variable T exists so that Comparator<Person> conforms to Comparator<? super T>
I'm thrown off by this error and I would like to know how to sort the Person array using cmp Comparator.