如何创建一个复合 Comparator 进行多条件排序

发布时间:2025-01-22 16:36:35 作者:小樊
来源:亿速云 阅读:81

在Java中,您可以使用Comparator接口创建一个复合Comparator以进行多条件排序

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Person {
    private String name;
    private int age;
    private String city;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getCity() {
        return city;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", city='" + city + '\'' +
                '}';
    }
}

public class MultiConditionSort {
    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person("Alice", 30, "New York"));
        people.add(new Person("Bob", 25, "San Francisco"));
        people.add(new Person("Charlie", 30, "Los Angeles"));
        people.add(new Person("David", 25, "New York"));

        Comparator<Person> sortByAgeThenName = Comparator
                .comparingInt(Person::getAge)
                .thenComparing(Person::getName);

        Comparator<Person> sortByCityThenAge = Comparator
                .comparing(Person::getCity)
                .thenComparingInt(Person::getAge);

        Collections.sort(people, sortByAgeThenName);
        System.out.println("Sort by age then name:");
        people.forEach(System.out::println);

        Collections.sort(people, sortByCityThenAge);
        System.out.println("\nSort by city then age:");
        people.forEach(System.out::println);
    }
}

在这个示例中,我们有一个Person类,包含姓名、年龄和城市属性。我们创建了两个复合Comparator:一个按年龄然后按姓名排序,另一个按城市然后按年龄排序。我们使用Collections.sort()方法对列表进行排序,并输出排序后的结果。

推荐阅读:
  1. 使用Java怎么实现一个比较器
  2. 怎么在Java中利用TreeMap实现一个排序算法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java Comparator 与 Lambda 表达式的结合使用

下一篇:Comparator 在 Java 中的应用案例有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》