I have an arrayList.
This is an arrayList of strings. The string contains a \"Date.toString\"
in format of \"January 1, 1970, 00:00:00 GMT\"
+
I would convert this array list first to something like
public class Event {
private Date date;
private String description;
...
}
After that, create a comparator to compare 2 events like this:
public class EventComparator implements Comparator<Event>{
public int compare(Event e1, Event e2) {
return e1.getDate().compareTo(e2.getDate());
}
}
This will save you tons of performance compared with (pardon me) parsing each string for each comparison.
Write a comparator in which, convert the strings to dates for comparison. Collections.sort(List, Comparator);
does the job after that.
Convert the array into a list of dates and then sort them:
List<Date> dates = new ArrayList<Date>();
for(String s : dateStringArray){
// split the date and task name
Pattern p = Pattern.compile("(\\w+ \\d{1,2}, \\d{4}, \\d{2}:\\d{2}:\\d{2} \\w{3})(.*)");
Matcher matcher = p.matcher(s);
String taskname = "";
String datestring = "";
if (matcher.find()) {
datestring = matcher.group(1);
taskname = matcher.group(2);
}
// parse the date
Date d = new SimpleDateFormat("MMMM dd, yyyy, HH:mm:ss z",
Locale.ENGLISH).parse(datestring);
dates.add(d);
}
// sort the dates
Collections.sort(dates);
If you want to keep the task names, you will have to make own objects that have the date and the task as fields and are comparable by the dates.
For each String
, convert it to a Date
, possibly using a SimpleDateFormat
, and put them all in a TreeMap<Date,String>
, which will sort them for you.
Edit: And as @Sean Patrick Floyd suggested, do it on input.
Write your own comparator. Then use Collections.sort(arrayList, myComparator);
Comparator<String> myComparator = new Comparator<String>() {
int compareTo(String string1, String string2) {
......
}
boolean equals(String str1) {
......
}
}
You could write a comparator that parses the dates and sorts them using date.compareTo(otherDate)
, but I'd suggest you store dates
instead of Strings
in the first place, making sorting much easier (Date implements Comparable<Date>
.
(If your input format is String
, then convert the Strings
at the time you add them to the list)