List针对指定字段进行排序

  • Post author:
  • Post category:其他


业务情况:前台显示的列表为拼接出来的字段,并不是由数据库中的某一张表直接查询出来的数据,需要针对list进行排序,但不能使用SQL中的order by ,因此java提供了针对List的自定义排序,这里只举例一种匿名内部类不限制字段类型的排序方法,通用!

示例:

class Record{
    public String name;
    public String sex;
    public int age;
    public Date birthday;
    public Record(String name,String sex,int age,Date birthday){
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.brithday = birthday;
    }
    generate getter and setter...
}
List demoList = new ArrayList();
demoList.add(new Record("张三","男",16,new Date()));
demoList.add(new Record("李四","女",18,new Date()));
//自定义排序,不限制字段类型
Collections.sort(demoList,new Comparator<Record>()
{
    @Override
    public int compare(Record r1,Record r2){
        //按照出生日期排序,正序
        return r1.getBirthday().compareTo(r2.getBirthday());
        //倒序
        return r2.getBirthday().compareTo(r1.getBirthday());
    }
});



版权声明:本文为qq_38078190原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。