[英]How to sort an object Array using a custom Comparator interface in Java 8?
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. 我创建了一个包含三个字段的Person类,即firstName,lastName和age,以及它们各自的getter和setter。 Using the custom Comparator class I want to sort an array of persons in main as under:
使用自定义Comparator类我想在main中对一组人员进行排序,如下所示:
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);
但是
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>
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. 我被这个错误抛弃了,我想知道如何使用
cmp
Comparator对Person数组进行排序。
The fully qualified name of a class
in Java includes it's package name. Java中
class
的完全限定名称包括它的包名。
The Arrays.sort method expects a java.util.Comparator
implementation. Arrays.sort方法需要
java.util.Comparator
实现。 Your custom Comparator
is not the same is java.util.Comparator
. 您的自定义
Comparator
与java.util.Comparator
。
The sort
method in Arrays
class is a static
method so you can't extend Arrays
and override this method. Arrays
类中的sort
方法是一个static
方法,因此您无法扩展Arrays
并覆盖此方法。 If you want to use Arrays.sort , use an implementation of java.util.Comparator
. 如果要使用Arrays.sort ,请使用
java.util.Comparator
的实现。 There is no way around it. 没有其他办法了。
You can easily adapt your Comparator
to the JDK's like this: 您可以轻松地将
Comparator
调整为JDK,如下所示:
Arrays.sort(arr, cmp::compare);
I believe Guava recommended a similar pattern to adapt their functional interfaces before they were retrofitted for Java 8. 我相信Guava建议使用类似的模式来修改它们的功能接口,然后再为Java 8进行改造。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.