繁体   English   中英

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

[英]sort array list of special strings, by date

我有一个arrayList。

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

例如:

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

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

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

(如果输入格式为String ,则在将Strings添加到列表时进行转换)

对于每个String ,可能使用SimpleDateFormat ,将其转换为Date ,并将它们全部放入TreeMap<Date,String> ,后者将为您排序。

编辑 :就像@Sean Patrick Floyd所建议的那样,在输入时执行。

我会先将此数组列表转换为类似

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

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

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

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

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

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

Comparator<String> myComparator = new Comparator<String>() {

 int compareTo(String string1, String string2) {
     ......
 }

 boolean equals(String str1) {
    ......
 }

}

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

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);

如果要保留任务名称,则必须创建自己的对象,这些对象将日期和任务作为字段,并且可以按日期进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM