如何使用集合对对象的属性进行排序 [英] How to sort an attribute of an object using Collections

查看:76
本文介绍了如何使用集合对对象的属性进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天!

我有一名具有以下属性的对象学生:

I have an object student with the following attributes:

class Student
    String name
    Date birthday

我用过用于存储学生对象的arrayList
我的问题是,如何使用collecitons排序按生日排序StudentList?。

I used arrayList to store the Student Objects My problem is, how can I sort the StudentList by birthday using the collecitons sort?.

List <Student> studentList = new ArrayList<Student>();

我该如何编码?

Collections.sort(????);

Collections.sort(????);

谢谢

推荐答案

您可以传递 比较器 Collections.sort() 按生日处理排序:

You can pass a Comparator to Collections.sort() to handle the sorting by birthday:

Collections.sort(studentList, new Comparator<Student>() {
    public int compare(Student s1, Student s2) {
        return s1.getBirthday().compareTo(s2.getBirthday());
    }
});

您需要添加 getBirthday()如果你还没有学生课程。

You'll need to add getBirthday() to your Student class if you don't have it already.

这篇关于如何使用集合对对象的属性进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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