Sorting Arrays by Multiple Fields in Java
When working with arrays of objects, the need often arises to sort them based on multiple criteria. In this case, the task is to sort an array of Person objects by name alphabetically and then by age.
Solution 1: Using a Custom Comparator
One approach is to use a custom Comparator to define the sorting criteria. This class implements the Comparator interface and overrides the compare method to specify the desired sorting logic.
Here's a code snippet that demonstrates this approach:
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); } }); }
This comparator first compares the names of the Person objects and, if they are equal, it compares their ages.
Method: Collections.sort
Algorithm: Merge Sort (used by Arrays.sort)
Time Complexity: O(n log n)
Benefit: Allows for flexible sorting criteria.
The above is the detailed content of How Can I Sort a Java Array of Objects by Multiple Fields?. For more information, please follow other related articles on the PHP Chinese website!