Reputation: 59
I have a class Person with the attributes of name (string) and age (int):
public class Person {
private String name;
private int age;
public Hero(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
I created a list of Person, and compared them using age.
List<Person> persons = new ArrayList<>();
persons.add("Andrew", 18);
persons.add("Barry", 25);
persons.add("Cynthia", 33);
persons.add("Darwin", 33);
Collections.sort(persons, new Comparator<Person>() {
@Override
public int compare(Person lhs, Person rhs) {
return lhs.getAge() < rhs.getAge() ? -1 : lhs.getAge() == lhs.getAge() ? 0 : 1;
}
});
If the ages of two items are equal, how do I compare them using the name instead?
Upvotes: 0
Views: 547
Reputation: 680
Starting with Java 8, creating a custom Comparator
is much easier, and you can compare multiple fields.
You can use the following code:
Comparator.comparing(Person::getAge).thenComparing(Person::getName)
And that's it.
You can use it to sort your collection like this:
Collections.sort(filteredList, Comparator.comparing(Person::getAge).thenComparing(Person::getName))
Upvotes: 2