Let's say I have a class Person that has methods getAge() and getYearsOfEducation(), both returning ints. Then I have another class Employer that has a method getYearsOfEmployment(Person p) for a given Person, also returning an 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
When I have a list of Persons (added randomly to the list), I want it sorted (1) by age, (2) by years of education, and (3) by years of employment (always least first) -- so in the above example, the final order should be p1, p4, p3, p2. It is clear to me how to sort by age and years of education, but I cannot figure out how to do the final sorting by years of employment since that is not a method of Person.
List<Person> persons = Arrays.asList(new Person[]{p1, p2, p3, p4});
Collections.sort(persons, Comparator.comparing(Person::getAge)
.thenComparing(Person::getYearsOfEducation)
.thenComparing(...));
Is what I want to do possible?
Employer eavailable before thatCollections#sortcall, it would just be.thenComparing(e::getYearsOfEmployment).