Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an attribute of an object using Collections

Tags:

java

Good day!

I have an object student with the following attributes:

class Student
    String name
    Date birthday

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>();

How can I code it?

Collections.sort(????);

Thank you

like image 292
newbie Avatar asked May 09 '11 05:05

newbie


People also ask

How do you sort objects in collections?

Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of List. Collections class provides methods for sorting the elements of List type elements.

How do you sort a list of objects based on an attribute of the objects in Java?

In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.

Which sorting is used in collections sort?

So, in the end, Collections#sort uses Arrays#sort (of object elements) behind the scenes. This implementation uses merge sort or tim sort.

What method of collections is used to sort elements in a list?

Summary. Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.


2 Answers

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());
    }
});

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

like image 160
WhiteFang34 Avatar answered Sep 18 '22 07:09

WhiteFang34


In Java 8 you can sort the list with a one-liner using Lambda expressions and Comparator.comparing:

Collections.sort(studentList, Comparator.comparing(s -> s.getBirthday()));

Alternatively you can use the method reference:

Collections.sort(studentList, Comparator.comparing(Student::getBirthday));
like image 24
Stefan Endrullis Avatar answered Sep 19 '22 07:09

Stefan Endrullis