Home >Java >javaTutorial >How to Sort Java Objects by Multiple Fields (Name and Age)?

How to Sort Java Objects by Multiple Fields (Name and Age)?

Susan Sarandon
Susan SarandonOriginal
2024-12-15 19:58:16458browse

How to Sort Java Objects by Multiple Fields (Name and Age)?

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

  1. Instantiate a Comparator by implementing the compare method.
  2. Compare the names of two objects (lexographically). If different, return the result.
  3. If names are equal, compare the ages and return the result.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn