I have some lists that contain elements of type DataTime( Joda-time ). How can I sort them by date? It will be great if somebody gave link to the example...
2 Answers
Because the objects of your list implement the Comparable interface, you can use
Collections.sort(list);
where list is your ArrayList.
Relevant Javadocs:
Edit: If you want to sort a list of a custom class that contains a DateTime field in a similar way, you would have to implement the Comparable interface yourself. For example,
public class Profile implements Comparable<Profile> {
DateTime date;
double age;
int id;
...
@Override
public int compareTo(Profile other) {
return date.compareTo(other.getDate()); // compare by date
}
}
Now, if you had a List of Profile instances, you could employ the same method as above, namely Collections.sort(list) where list is the list of Profiles.
DateTime already implements Comparable you just need to use Collections.sort()
5 Comments
Stas0n
And what if the ArrayList contains objects of class Profile public Profile{ DateTime date; Double age; int id; } How can i sort it by date?
Jigar Joshi
You need to implement custom comparator in this case
arshajii
@Stas0n see the edit on my post
Stas0n
Could you show a sketch of the code?
Jigar Joshi
Collections.sortandComparator.