sort array list of special strings, by date

前端 未结 6 599
有刺的猬
有刺的猬 2021-01-25 10:33

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\" +

相关标签:
6条回答
  • 2021-01-25 10:49

    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.

    0 讨论(0)
  • 2021-01-25 10:52

    Write a comparator in which, convert the strings to dates for comparison. Collections.sort(List, Comparator); does the job after that.

    0 讨论(0)
  • 2021-01-25 10:52

    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.

    0 讨论(0)
  • 2021-01-25 10:53

    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.

    0 讨论(0)
  • 2021-01-25 10:57

    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) {
        ......
     }
    
    }
    
    0 讨论(0)
  • 2021-01-25 11:04

    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)

    0 讨论(0)
提交回复
热议问题