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.