How to sort an attribute of an object using Collections

后端 未结 6 901
眼角桃花
眼角桃花 2020-12-03 11:52

Good day!

I have an object student with the following attributes:

class Student
    String name
    Date birthday

I used arrayList

6条回答
  •  孤街浪徒
    2020-12-03 12:20

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

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

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

提交回复
热议问题