0

I have a Person class that has 2 fields, one is name, and the other is age, I would like to sort by age first and then by name.

Simple code is as follows:

import java.util.ArrayList;
import java.util.List;

public class Person {
    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "Person{" + "name='" + name + '\'' + ", age=" + age + '}';
    }

    String name;
    int age;


    public static List<Person> getPersons() {
        List<Person> persons = new ArrayList<>();
        Person p1 = new Person();
        p1.name = "Jack";
        p1.age = 29;
        persons.add(p1);

        p1 = new Person();
        p1.name = "Tom";
        p1.age = 27;
        persons.add(p1);

        p1 = new Person();
        p1.name = "Don";
        p1.age = 27;
        persons.add(p1);

        return persons;
    }

}

Test code is:

    @Test
    public void testComparator() {
        List<Person> persons = Person.getPersons();
        persons.sort(Comparator.comparing(p->p.getAge()).thenComparing(p->p.getName()));
        System.out.println(persons);
    }

It complains that getAge and getName are not methods of Object, I would ask where the problem is.

Tom
  • 5,848
  • 12
  • 44
  • 104
  • 4
    As an aside, have you tried `Person::getAge` and `Person::getName` instead? (EDIT: turns out it's not an aside, but an actual possible solution, see linked duplicate) – Federico klez Culloca Jan 17 '23 at 07:47
  • 3
    The compiler would have issues with inferring the type of `p` in the lambdas so you need to help it: `(Person p) -> p.getAge()` etc. - `Person::getAge` basically contains that type info "out of the box". – Thomas Jan 17 '23 at 07:50
  • @Thomas – Perhaps you should make this the answer, after adding some additional flesh? – tquadrat Jan 17 '23 at 08:00
  • @tquadrat it's been closed as a duplicate. It can't (and doesn't need to) be answered. – Federico klez Culloca Jan 17 '23 at 08:00
  • @tquadrat to add to Federico's comment: the duplicate he's linked already contains a very good and extensive answer so there's no need to add another :) – Thomas Jan 17 '23 at 08:01
  • @Thomas – Seemed that I added my comment only seconds, maximum minutes before the question was closed. – tquadrat Jan 17 '23 at 19:51

0 Answers0