-2

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...

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Stas0n
  • 127
  • 1
  • 10

2 Answers2

9

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.

arshajii
  • 127,459
  • 24
  • 238
  • 287
6

DateTime already implements Comparable you just need to use Collections.sort()

kleopatra
  • 51,061
  • 28
  • 99
  • 211
jmj
  • 237,923
  • 42
  • 401
  • 438