按照对象中的不同参数对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}

相关内容

热门资讯

透视新版!wepoker私人局... 透视新版!wepoker私人局可以透视(透视)西部透视辅助(果然是有辅助软件)-哔哩哔哩在进入西部透...
据玩家消息!德州辅助工具到底怎... 据玩家消息!德州辅助工具到底怎么样(透视)微信小程序边锋辅助下载(竟然有辅助安装)-哔哩哔哩1、每一...
透视最新!红龙poker辅助平... 透视最新!红龙poker辅助平台(透视)鸿狐拼十辅助(果然真的有辅助插件)-哔哩哔哩1、起透看视 鸿...
为切实保障!wepoker辅助... 为切实保障!wepoker辅助是真的吗(透视)哈灵脚本修改器(确实是真的辅助修改器)-哔哩哔哩1、不...
透视了解!wepoker怎么挂... 透视了解!wepoker怎么挂底牌(透视)心悦辅助(原来存在有辅助软件)-哔哩哔哩1.心悦辅助 选牌...
为切实保障!wepoker手机... 为切实保障!wepoker手机插件(透视)川娱竞技辅助(一贯真的有辅助辅助器)-哔哩哔哩1、点击下载...
透视玄学!pokerrrr2辅... 透视玄学!pokerrrr2辅助(透视)微信插件激活码(真是真的是有辅助插件)-哔哩哔哩1、微信插件...
透视新版!拱趴大菠萝机器人(透... 透视新版!拱趴大菠萝机器人(透视)越乡游双扣辅助器(果然是真的辅助安装)-哔哩哔哩1、起透看视 越乡...
透视肯定!aapoker如何设... 透视肯定!aapoker如何设置胜率(透视)吉祥填大坑怎么用插件(果然真的有辅助神器)-哔哩哔哩1、...
无独有偶!fishpoker透... 无独有偶!fishpoker透视底牌(透视)新九游辅助软件(真是是真的辅助插件)-哔哩哔哩运新九游辅...