按日期排序特殊字符串的数组列表

我有一个arrayList。

这是一个字符串数组列表。 该字符串包含格式为"January 1, 1970, 00:00:00 GMT" +任务名称的"Date.toString"

例如:

 "January 1, 1970, 00:00:00 GMT clean the house". 

我想按日期排序这个arrayList。
我该怎么做?

可以编写一个比较器来解析日期并使用date.compareTo(otherDate)它们进行排序,但我建议您首先存储dates而不是Strings ,使排序更容易(Date实现Comparable

(如果您的输入格式是String ,那么在将它们添加到列表时转换Strings

对于每个String ,可以使用SimpleDateFormat将其转换为Date ,并将它们全部放在TreeMap ,它将为您排序。

编辑 :正如@Sean Patrick Floyd建议的那样,在输入时做。

我会先把这个数组列表转换成类似的东西

 public class Event { private Date date; private String description; ... } 

之后,创建一个比较器来比较2个事件,如下所示:

 public class EventComparator implements Comparator{ public int compare(Event e1, Event e2) { return e1.getDate().compareTo(e2.getDate()); } } 

与(原谅我)解析每个比较的每个字符串相比,这将节省大量的性能。

写一个比较器,在其中将字符串转换为日期以进行比较。 Collections.sort(List, Comparator); 在那之后完成工作。

编写自己的比较器。 然后使用Collections.sort(arrayList, myComparator);

 Comparator myComparator = new Comparator() { int compareTo(String string1, String string2) { ...... } boolean equals(String str1) { ...... } } 

将数组转换为日期列表,然后对它们进行排序:

 List dates = new ArrayList(); 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); 

如果要保留任务名称,则必须创建自己的对象,其日期和任务为字段,并且与日期相当。