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

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

DDD
DDDOriginal
2024-12-28 02:49:09713browse

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

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:

  • Collections.sort: This method provides the sorting functionality.
  • Comparator: We create an anonymous inner class that implements the Comparator interface. The compare method defines how to compare two Person objects.
  • Name Comparison: First, it compares the names of the Person objects using String.compareTo.
  • Age Comparison: If the names are equal, it compares the ages of the Person objects using Integer.compareTo.

After sorting the list using the custom comparator, the List will be sorted by name in ascending order and by age in ascending order within the same name.

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!

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