Java Multi-Condition Sorting Guide

In Java, the use of the Comparator interface allows for the implementation of multi-level sorting. The compare method in the Comparator interface allows for the specification of multiple comparison conditions, which can then be utilized for sorting with multiple criteria.

Here is an example code demonstrating how to implement multi-condition sorting.

import java.util.Comparator;

public class MultiConditionSort {

    public static void main(String[] args) {
        // 定义一个Person类
        class Person {
            String name;
            int age;

            public Person(String name, int age) {
                this.name = name;
                this.age = age;
            }

            @Override
            public String toString() {
                return name + " - " + age;
            }
        }

        // 创建一个Person对象数组
        Person[] people = {
                new Person("Alice", 30),
                new Person("Bob", 25),
                new Person("Charlie", 35),
                new Person("David", 20)
        };

        // 定义一个Comparator,实现多条件排序
        Comparator<Person> comparator = Comparator
                .comparing((Person p) -> p.age) // 按年龄升序排序
                .thenComparing(p -> p.name);     // 年龄相同时,按姓名升序排序

        // 使用Comparator进行排序
        Arrays.sort(people, comparator);

        // 打印排序结果
        for (Person person : people) {
            System.out.println(person);
        }
    }
}

In the example above, we defined a Person class with two attributes: name and age. We then created an array of Person objects and defined a Comparator to sort by multiple conditions – first by age in ascending order, and then by name in ascending order if the ages are the same. Finally, we used the Arrays.sort method to sort the Person array and printed the results.

In this way, we can easily achieve multi-condition sorting.

bannerAds