Can someone help me with this? Every example I find is about doing this alphabetically, while I need my elements sorted by date.
My ArrayList contains objects on which one of the datamembers is a DateTime object. On DateTime I can call the functions:
lt() // less-than
lteq() // less-than-or-equal-to
So to compare I could do something like:
if(myList.get(i).lt(myList.get(j))){
// ...
}
I don't really know what to do inside the if block. Any ideas?
This is how I solved:
Hope it help you.
Pass the ArrayList In argument.
This may be an old response but I used some examples from this post to create a comparator that would sort an
ArrayList
ofHashMap<String, String>
by one object in the list, that being the timestamp.I have these objects:
The map objects are as follows:
That mapping is what I use to load all my objects into the array list, using the
alList.add(map)
function, within a loop.Now, I created my own comparator:
I can now just call the Comparator at any time on the array and it will sort my array, giving me the Latest timestamp in position 0 (top of the list) and the earliest timestamp at the end of the list. New posts get put to the top basically.
This may help someone out, which is why I posted it. Take into consideration the return statements within the compare() function. There are 3 types of results. Returning 0 if they are equal, returning >0 if the first date is before the second date and returning <0 if the first date is after the second date. If you want your list to be reversed, then just switch those two return statements! Simple =]
You can use Collections.sort method. It's a static method. You pass it the list and a comparator. It uses a modified mergesort algorithm over the list. That's why you must pass it a comparator to do the pair comparisons.
Note that if myList is of a comparable type (one that implements Comparable interface) (like Date, Integer or String) you can omit the comparator and the natural ordering will be used.
Given
MyObject
that has aDateTime
member with agetDateTime()
method, you can sort anArrayList
that containsMyObject
elements by theDateTime
objects like this:You can make your object comparable:
And then you sort it by calling:
However sometimes you don't want to change your model, like when you want to sort on several different properties. In that case, you can create comparator on the fly:
However, the above works only if you're certain that dateTime is not null at the time of comparison. It's wise to handle null as well to avoid NullPointerExceptions:
Or in the second example: