使用 Comparator- 降序排序(用户定义的类) [英] Sorting using Comparator- Descending order (User defined classes)

查看:27
本文介绍了使用 Comparator- 降序排序(用户定义的类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用比较器按降序对对象进行排序.

I want to sort my objects in descending order using comparator.

class Person {
 private int age;
}

这里我想对一组 Person 对象进行排序.

Here I want to sort a array of Person objects.

我该怎么做?

推荐答案

您可以通过这种方式对用户定义的类进行降序排序,覆盖 compare() 方法,

You can do the descending sort of a user-defined class this way overriding the compare() method,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return b.getName().compareTo(a.getName());
    }
});

使用Collection.reverse()他的评论.

Or by using Collection.reverse() to sort descending as user Prince mentioned in his comment.

你可以像这样进行升序排序,

And you can do the ascending sort like this,

Collections.sort(unsortedList,new Comparator<Person>() {
    @Override
    public int compare(Person a, Person b) {
        return a.getName().compareTo(b.getName());
    }
});

用 Lambda 表达式(Java 8 以后)替换上面的代码,我们会变得简洁:

Replace the above code with a Lambda expression(Java 8 onwards) we get concise:

Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));

从 Java 8 开始,List 具有 sort() 方法采用 Comparator 作为参数(更简洁):

As of Java 8, List has sort() method which takes Comparator as parameter(more concise) :

personList.sort((a,b)->b.getName().compareTo(a.getName()));

这里的 ab 被 lambda 表达式推断为 Person 类型.

Here a and b are inferred as Person type by lambda expression.

这篇关于使用 Comparator- 降序排序(用户定义的类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆