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

4
  • Look into Collections.sort and Comparator. Commented Oct 10, 2012 at 21:05
  • @nkr I think you mean Comparator Commented Oct 10, 2012 at 21:06
  • Hint: sort by timestamp. Commented Oct 10, 2012 at 21:06
  • Can you show the outline of the code? Commented Oct 10, 2012 at 21:07

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
Profile is a class, that i wrote myself
6

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

5 Comments

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?
You need to implement custom comparator in this case
@Stas0n see the edit on my post
Could you show a sketch of the code?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.