Home >Java >javaTutorial >How to Sort a List of Objects by Multiple Fields in Java?
Sorting Objects by Multiple Fields in Java
Sorting data by multiple fields is a common operation in programming. This question explores how to sort an array of person objects alphabetically by name and then by age.
Using Collections.sort for Multi-Field Sorting
To achieve this, we can leverage the Collections.sort method, which allows for custom sorting based on a provided Comparator. The Comparator determines how two objects should be compared, enabling us to define a multi-field sorting strategy.
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); }}); }
In this code, the compare method first compares the names of the two person objects (x1 and x2). If they are different, it returns the result of the String.compareTo method, indicating which string is lexicographically greater. If the names are equal, it proceeds to compare the ages (x1 and x2) using the compareTo method for Integer objects.
By using this Comparator strategy, the Collections.sort method will sort the list of person objects alphabetically by name, and if the names are equal, it will further sort them by age.
The above is the detailed content of How to Sort a List of Objects by Multiple Fields in Java?. For more information, please follow other related articles on the PHP Chinese website!