Java Sort List by Multiple Fields
In Java, multiple fields in a List can be sorted by implementing the Comparator interface. The compare method in the Comparator interface can compare and sort the values of multiple fields.
For example, suppose there is an object Person with multiple fields, a custom comparator class implementing the Comparator interface can be created to sort Person objects.
import java.util.Comparator;
public class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person p1, Person p2) {
// 先按照age字段进行升序排序
int result = Integer.compare(p1.getAge(), p2.getAge());
if (result == 0) {
// 如果age字段相等,则按照name字段进行升序排序
result = p1.getName().compareTo(p2.getName());
}
return result;
}
}
Next, you can use the sort method of the Collections utility class to sort the List and pass in a custom comparator class.
List<Person> personList = new ArrayList<>();
// 添加Person对象到personList中
Collections.sort(personList, new PersonComparator());
This allows for sorting of Person objects in a List in ascending order based on the age field, and if the age field is the same, then sorting is done in ascending order based on the name field. You can modify the compare method in a custom comparator class to implement different multi-field sorting logic as needed.