假設我有一個類Person,它有方法getAge()和getYearsOfEducation(),都回傳ints。然后我有另一個類Employer,它有一個getYearsOfEmployment(Person p)給定的方法Person,也回傳一個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
當我有一個Persons 串列(隨機添加到串列中)時,我希望它按(1)按年齡排序,(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(...));
我想做的事可能嗎?
uj5u.com熱心網友回復:
正如@Rogue在評論中所說,您需要參考Employer.
如果所有Person實體都屬于同一個Employer,那么您可以在(或者,您可以使用)的keyExtractor函式中使用它:thenComparing() 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);
whereemployer::getYearsOfEmployment等效于以下 lambda 運算式:
person -> employer.getYearsOfEmployment(person)
它應該被限定為對特定物件的實體方法的參考
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527760.html
標籤:爪哇列表排序比较器
上一篇:如何按順序添加Python串列?
