假设我有一个类Person,它有方法getAge()和getYearsOfEducation(),它们都返回ints,然后我有另一个类Employer,它有一个给定Person的方法getYearsOfEmployment(Person p),也返回一个int。
Employer e = new Employer();
Person p1 = new Person(26, 3) // age and years of education
Person p2 = new Person(30, 4)
Person p3 = new Person(28, 5) // let's say that e.getYearsOfEmployment(p3) returns 10
Person p4 = new Person(28, 5) // let's say that e.getYearsOfEmployment(p4) returns 8当我有一个Person的列表(随机添加到列表中)时,我希望它按年龄、(2)按教育程度、(3)按就业年限(总是最不首先)排序--所以在上面的示例中,最后的顺序应该是p1、p4、p3、p2。我很清楚如何按年龄和教育年限进行分类,但我不知道如何按就业年限进行最后排序,因为这不是Person的一种方法。
List<Person> persons = Arrays.asList(new Person[]{p1, p2, p3, p4});
Collections.sort(persons, Comparator.comparing(Person::getAge)
.thenComparing(Person::getYearsOfEducation)
.thenComparing(...));我想做什么是可能的吗?
发布于 2022-11-04 15:25:16
作为在评论中说,您需要对Employer实例的引用。
如果所有Person实例都属于同一个Employer,那么您可以在thenComparing()的keyExtractor函数中使用它(或者可以使用thenComparingInt()):
List<Person> persons = Arrays.asList(new Person[]{p1, p2, p3, p4});
Employer employer = // initializing the employer
Collections.sort(persons, Comparator.comparing(Person::getAge)
.thenComparing(Person::getYearsOfEducation)
.thenComparing(employer::getYearsOfEmployment);其中,employer::getYearsOfEmployment相当于以下lambda表达式:
person -> employer.getYearsOfEmployment(person)它应该被限定为对特定对象的实例方法的引用
https://stackoverflow.com/questions/74318979
复制相似问题