Java Multi-Condition Sorting Guide
In Java, the Comparator interface can be used to implement multi-condition sorting. This interface includes a compare method where multiple conditions can be written to define the sorting rules. Below is an example code:
Let’s say there is a Person class that has attributes of name and age.
public class Person {
private String name;
private int age;
// 构造方法和getter/setter略
}
We want to sort in ascending order by age, and if ages are the same, then sort alphabetically by name.
List<Person> people = new ArrayList<>();
// 添加Person对象到people列表
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
if (p1.getAge() != p2.getAge()) {
return p1.getAge() - p2.getAge();
} else {
return p1.getName().compareTo(p2.getName());
}
}
});
In this example, we used an anonymous inner class to implement the Comparator interface and override the compare method to define the sorting rule. We first compare by age, sorting in ascending order, and if the ages are the same, we then compare by name, sorting in alphabetical order. Finally, we sort the list using the Collections.sort method.