Java比较器排序——通过ArrayList及PriorityQueue

 下面的代码实现了

1. 使用 Collections.sort 对 ArrayList 从大到小排序

2. 使用  PriorityQueue 对自定义的person类排序,要求:age小的靠前,age一样,名字长的靠前

public class SortTest {
    public static void main(String[] args) {

        int[] arr = {5, 2, 3, 6, 9, 1};
        ArrayList<Integer> arrayList = new ArrayList<Integer>();
        for (int i = 0; i < arr.length; i++) {
            arrayList.add(arr[i]);
        }
        // collections 排序
        Collections.sort(arrayList);
        System.out.println(arrayList);

        // collections 排序+比较器
        Collections.sort(arrayList, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                // 返回负数:o1 o2
                return o2-o1;
            }
        });
        System.out.println(arrayList);

        // PriorityQueue+比较器
        // 年龄越小越靠前,年龄一样,名字越长越靠前
        PriorityQueue<Person> persons = new PriorityQueue<Person>(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {
                if(o1.age != o2.age){
                    return o1.age - o2.age;
                } else {
                    return o2.name.length() - o1.name.length();
                }
            }
        });

        persons.add(new Person("john", 38));
        persons.add(new Person("marry", 38));
        persons.add(new Person("li", 30));

        while (!persons.isEmpty()) {
            System.out.println(persons.poll());
        }

    }
}

class Person {
    String name;
    Integer age;

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

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

比较器

new Comparator<Person>() {
    @Override
    public int compare(Person o1, Person o2) {
        if(o1.age != o2.age){
            return o1.age - o2.age;
        } else {
            return o2.name.length() - o1.name.length();
        }
    }

当返回负数时 o1在前面,可记:负数是o1 o2 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值