Multi-Field Sorting in Java
Sorting arrays of objects by multiple fields is a common requirement in programming. In this question, we want to sort an array of Person objects by name and then by age.
Solution:
To accomplish this, we can leverage the Collections.sort method along with a custom Comparator implementation. A comparator is a class that defines the comparison logic for two objects. In our case, we need a comparator that compares Person objects based on name first and age as a fallback.
private static void order(List<Person> persons) { Collections.sort(persons, new Comparator() { public int compare(Object o1, Object o2) { String x1 = ((Person) o1).getName(); String x2 = ((Person) o2).getName(); int sComp = x1.compareTo(x2); if (sComp != 0) { return sComp; } Integer x1 = ((Person) o1).getAge(); Integer x2 = ((Person) o2).getAge(); return x1.compareTo(x2); }}); }
Explanation:
After sorting the list using the custom comparator, the List
The above is the detailed content of How to Sort a Java Array of Objects by Multiple Fields (Name and Age)?. For more information, please follow other related articles on the PHP Chinese website!