static class Person {
final String firstName;
final String lastName;
Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return "Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
Person的数据有:
List<Person> people =
Arrays.asList(
new Person("Jane", "Henderson"),
new Person("Michael", "White"),
new Person("Henry", "Brighton"),
new Person("Hannah", "Plowman"),
new Person("William", "Henderson")
);
people.sort(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int result = o1.lastName.compareTo(o2.lastName);
if (result == 0)
result = o1.firstName.compareTo(o2.firstName);
return result;
}
});
people.forEach(System.out::println);
而在Java 8中,我们可以使用lambda替代匿名函数,如下:
Comparator<Person> c = (p, o) -> p.lastName.compareTo(o.lastName);
c = c.thenComparing((p, o) -> p.firstName.compareTo(o.firstName));
people.sort(c);
people.forEach(System.out::println);