-6

I have an array list with times. I want to sort it in time Ascending order. I used this but it does not output what I want.

List<String> l = new ArrayList<>();
l.add("12:20 PM");
l.add("12:32 PM");
l.add("12:30 PM");
l.add("12:10 PM");
l.add("12:08 PM");
l.add("12:00 PM");
Collections.sort(l, new Comparator<String>() { 
  @Override
  public int compare(String o1, String o2) {
    try {
      return new SimpleDateFormat("h:mm a").parse(o1).compareTo(new SimpleDateFormat("hh:mm a").parse(o2));
    } catch (ParseException e) {
      return 0;
    }
  }
 });
System.out.println(l);

I need:

12:00 PM
12:08 PM
12:10 PM...

Likewise

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
JOHN MORGAN
  • 113
  • 4
  • 12

2 Answers2

1

Lets start here:

} catch (ParseException e) {
    return 0;
}

ParseException means parsing went wrong. You are suppressing that and turn it into: the two strings equal the same time.

Simply don't do that.

Then I would also suggest to not store strings, but Date objects in that list. You have to understand that each and any compare causes those formatting steps. In other words, sorting on strings instead of dates causes an enormous overhead here!

In other words, turn all strings into dates first and then sort the dates.

Michael
  • 41,989
  • 11
  • 82
  • 128
GhostCat
  • 137,827
  • 25
  • 176
  • 248
0

Your date format is wrong:

try {
    return new SimpleDateFormat("h:mm a").parse(o1).compareTo(new SimpleDateFormat("hh:mm a").parse(o2));
} catch (ParseException e) {
    return 0;
}

It should be hh:mm a because there are two digits which represent the hour in your examples.

This is causing a ParseException because your strings do not match the format. The exception is handled as treating the strings as identical. This is not a good way to handle that error.

Therefore, because no strings match the format, every comparison results in an exception, which treats the strings as identical and so nothing gets re-ordered.

Michael
  • 41,989
  • 11
  • 82
  • 128
  • On my computer it parsed nicely and correctly with `h:mm a` even though there are two digits in the hours in `12:20 PM`, etc. – Ole V.V. May 08 '17 at 16:17