Sorting Java Objects by Multiple Fields: Name and Age
Consider an array of Person objects, each containing an integer age and a String name. Sorting such an array alphabetically by name and then by age requires a custom sorting algorithm.
Using Collections.sort
The Java Collections library provides a built-in sort method you can leverage:
private static void order(List<Person> persons) { Collections.sort(persons, new Comparator<>() { @Override public int compare(Object o1, Object o2) { // Compare by name (lexicographically) String x1 = ((Person) o1).getName(); String x2 = ((Person) o2).getName(); int sComp = x1.compareTo(x2); // If names are different, return result if (sComp != 0) { return sComp; } // If names are equal, compare by age Integer x1 = ((Person) o1).getAge(); Integer x2 = ((Person) o2).getAge(); return x1.compareTo(x2); } }); }
Process Flow
By invoking Collections.sort with this custom Comparator, you can sort the array of Person objects in ascending order of name, followed by ascending order of age.
The above is the detailed content of How to Sort Java Objects by Multiple Fields (Name and Age)?. For more information, please follow other related articles on the PHP Chinese website!