Search code examples
javacollectionscompareto

Sort List of object based on start date of the course


I need to sort a list of courses with a start date the dates is Strings.

The sort should be based on the start date, my date in the list is looks like:

  • 03:20
  • 04:10
  • 09:40
  • 08:00
  • 08:50
  • 01:50
  • 02:30

Note That the sort here is custom and every item with start date from 01 until 07 should be below dates from 08 until 12

for example the list above will be:

  • 08:00
  • 08:50
  • 09:40
  • 01:50
  • 02:30
  • 03:20
  • 04:10

How can I achieve this, I tried this:

int compare = this.getStartDate().compareTo(o.getStartDate());
if (compare > 0 && this.getStartDate().charAt(1) >= '1' && this.getStartDate().charAt(1) <= '7')
        return -1;
if (compare < 0 && o.getStartDate().charAt(1) < '1' && o.getStartDate().charAt(1) > '7')
        return 1;
return compare;

Solution

  • Use this method that converts the times below "08:00" to times greater than "12:00" by adding 12 to the hour part:

    public static String getValue(String s) {
        String[] splitted = s.split(":");
        int hour = Integer.parseInt(splitted[0]);
        if (hour < 8) {
            hour += 12;
            splitted[0] = String.valueOf(hour);
        }
        return splitted[0] + ":" + splitted[1];
    }
    

    now compare like this:

    return getValue(this.getStartDate()).compareTo(getValue(o.getStartDate()));