Home > Java > javaTutorial > How Can I Sort a Java Array of Objects by Multiple Fields?

How Can I Sort a Java Array of Objects by Multiple Fields?

DDD
Release: 2024-12-23 04:39:47
Original
368 people have browsed it

How Can I Sort a Java Array of Objects by Multiple Fields?

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);
        }
    });
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template