date comparison inside a list returned
I have a ArrayList returned from a service which contains date-timestamp as String values (with values: 2010-05-06T23:38:18,开发者_JS百科2010-05-06T23:32:52,2010-04-28T18:23:06,2010-04-27T20:34:02,2010-04-27T20:37:02)
to be more specific, This is part of a parent ArrayList ObjectHistory. This list contains the datestamp and serial number. I need to pick the correct serial number.
Objecthistory is the List object and I need to get the latest timestamp within this ObjectHistory.
I need to pick the latest timestamp from this Arraylist in Java 6.
How should I be doing this? Should I do convert these values into calendar-time? I am in panic mode as this has to be done directly in production.
I would use TreeMap. For example,
TreeMap<String, String> map = new TreeMap<String, String>();
map.put(timestamp1, serial1);
map.put(timestmap2, serail2);
...
String latestTimestamp = map.lastKey();
String latestSerial = map.get(lastestTimestamp);
Assuming you mean the arraylist contains Date Objects (i.e. it is of type ArrayList) you can simply use Collections.sort()
If the list contains Long values (i.e. the timestamp values) the same thing will work.
Edit: Added in a javadoc link to the Collections.sort() method
Additional Edit:
For additional clarification on comparators:
You would make a comparator for your ObjectHistory class:
public class ObjectHistoryComparator impelements Comparator<ObjectHistory> {
public int compare(ObjectHistory o1, ObjectHistory o2) {
return o1.getDateTime().compareTo(o2.getDateTime());
}
}
What this does for you is allows you to use the default comparison of the dateTime format (whether it is a String or whatever) and then you can pass this into a sorter:
Collections.sort(array, new ObjectHistoryComparator());
Hope this helps out.
For converting your ISO 8601 dates to Java date time objects, you might take a look at the Joda Time library.
精彩评论