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

相关内容

热门资讯

重要通知!微乐小程序麻将自建房... 重要通知!微乐小程序麻将自建房辅助工具插件,微乐自建房脚本免费入口(开挂自建房)攻略1、起透看视 微...
最新技巧!微乐自建房辅助工具脚... 最新技巧!微乐自建房辅助工具脚本,微乐小程序免费黑科技(开挂自建房)器小薇(辅助器软件下载)致您一封...
重大通报!微信微乐自建房辅助工... 重大通报!微信微乐自建房辅助工具,微乐家乡麻将自建房辅助app(开挂自建房)工具暗藏猫腻,小编详细说...
分享个大家!微乐自建房辅助工具... 分享个大家!微乐自建房辅助工具免费app,微乐自建房脚本免费入口(开挂自建房)工具1、每一步都需要思...
大神推荐!微乐家乡麻将自建房辅... 大神推荐!微乐家乡麻将自建房辅助app,微乐小程序免费黑科技(开挂自建房)教程所有人都在同一条线上,...
一分钟了解!微信卡五星辅助器,... 一分钟了解!微信卡五星辅助器,微乐家乡麻将自建房辅助app(开挂自建房)app1、很好的工具软件,可...
盘点一款!微乐自建房辅助工具神... 盘点一款!微乐自建房辅助工具神器,微乐自建房脚本免费入口(开挂自建房)教程1、任何微乐自建房辅助工具...
分享实测!微乐自建房辅助工具,... 分享实测!微乐自建房辅助工具,微乐小程序免费黑科技(开挂自建房)软件1、首先打开微乐自建房辅助工具辅...
推荐一款!微乐微信自建房辅助工... 推荐一款!微乐微信自建房辅助工具插件,微乐小程序免费黑科技(开挂自建房)插件1、任何微乐微信自建房辅...
实测揭晓!微乐自建房辅助工具插... 实测揭晓!微乐自建房辅助工具插件,微乐家乡麻将自建房辅助app(开挂自建房)攻略;所有人都在同一条线...