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>
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.
The fully qualified name of a class
in Java includes it's package name.
The Arrays.sort method expects a java.util.Comparator
implementation. Your custom Comparator
is not the same is java.util.Comparator
.
The sort
method in Arrays
class is a static
method so you can't extend Arrays
and override this method. If you want to use Arrays.sort , use an implementation of java.util.Comparator
. There is no way around it.
You can easily adapt your Comparator
to the JDK's like this:
Arrays.sort(arr, cmp::compare);
I believe Guava recommended a similar pattern to adapt their functional interfaces before they were retrofitted for Java 8.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.