Home > Enterprise >  Sorting a list of objects using multiple fields (Java 8)
Sorting a list of objects using multiple fields (Java 8)

Time:11-05

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?

CodePudding user response:

As @Rogue has said in the comment you need a reference to an instance of Employer.

In case if all Person instances belong to the same Employer, then you can use it in the keyExtractor function of thenComparing() (alternatively, you can use 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);

Where employer::getYearsOfEmployment is an equivalent of the following lambda expression:

person -> employer.getYearsOfEmployment(person)

And it should be qualified as a Reference to an Instance Method of a Particular Object

  • Related