按照对象中的不同参数对ArrayList进行排序
创始人
2024-08-23 19:00:44
0

要按照对象中的不同参数对ArrayList进行排序,可以使用Comparator接口来定义排序规则,并使用Collections.sort()方法对ArrayList进行排序。下面是一个示例代码:

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

class Person {
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

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

class PersonNameComparator implements Comparator {
    @Override
    public int compare(Person p1, Person p2) {
        return p1.getName().compareTo(p2.getName());
    }
}

class PersonAgeComparator implements Comparator {
    @Override
    public int compare(Person p1, Person p2) {
        return Integer.compare(p1.getAge(), p2.getAge());
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayList persons = new ArrayList<>();
        persons.add(new Person("John", 25));
        persons.add(new Person("Alice", 18));
        persons.add(new Person("Bob", 30));

        // 按照姓名排序
        Collections.sort(persons, new PersonNameComparator());
        System.out.println("按照姓名排序:");
        for (Person person : persons) {
            System.out.println(person);
        }

        // 按照年龄排序
        Collections.sort(persons, new PersonAgeComparator());
        System.out.println("按照年龄排序:");
        for (Person person : persons) {
            System.out.println(person);
        }
    }
}

输出结果:

按照姓名排序:
Person{name='Alice', age=18}
Person{name='Bob', age=30}
Person{name='John', age=25}
按照年龄排序:
Person{name='Alice', age=18}
Person{name='John', age=25}
Person{name='Bob', age=30}

相关内容

热门资讯

玩家必看攻略!红龙poker辅... 玩家必看攻略!红龙poker辅助工具,pokernow辅助工具,详细教程(有挂辅助)是一款可以让一直...
推荐一款!poker worl... 推荐一款!poker world辅助,hhpkoer辅助挂是真的吗,透明挂教程(有挂神器)这是由厦门...
我来教教大家!newpoker... 我来教教大家!newpoker脚本,wepoker辅助插件功能,解说技巧(有挂神器);建议优先通过w...
信息共享!wejoker透视方... 信息共享!wejoker透视方法,hhpoker辅助挂下载,科技教程(有挂攻略);致您一封信;亲爱h...
玩家攻略!hhpoker透视脚... 玩家攻略!hhpoker透视脚本视频,hhpoker辅助软件,必备教程(有挂攻略);1分钟了解详细教...
推荐一款!aapoker如何设... 此外,数据分析德州(aapoker如何设置胜率)辅助神器app还具备辅助透视行为开挂功能,通过对客户...
如何分辨真伪!约局吧德州真的有... 如何分辨真伪!约局吧德州真的有透视挂吗,aapoker怎么拿好牌,2025新版(有挂方法)1、许多玩...
实操分享!wepoker可以透... 实操分享!wepoker可以透视码,pokermaster脚本,详细教程(有挂技巧)1、玩家可以在w...
发现一款!hhpoker辅助挂... 发现一款!hhpoker辅助挂下载,pokemmo脚本,揭秘教程(有挂技巧);hhpoker辅助挂下...
最新技巧!德州辅助工具到底怎么... 最新技巧!德州辅助工具到底怎么样,wepoker辅助真的假的,技巧教程(有挂透明);大神普及一款德州...