I have a List that contains a list of times from 8:00 am to 4:00 pm.
When I show it in output it appears unsorted, and when I use Collections.sort(myList); it sorts it as from 1:00 pm to 8:00 am.
How could I sort my list from 8:00am to 4:00pm ?
解决方案
Don't reinvent the wheel, use collection (or Lambdas if java8 is allowed)
How??:
keep the list as strings, but use an Anonymous comparator, in there, parse the string to dates, compare them and there you have it.
here a snippet:
List l = new ArrayList();
l.add("8:00 am");
l.add("8:32 am");
l.add("8:10 am");
l.add("1:00 pm");
l.add("3:00 pm");
l.add("2:00 pm");
Collections.sort(l, new Comparator() {
@Override
public int compare(String o1, String o2) {
try {
return new SimpleDateFormat("hh:mm a").parse(o1).compareTo(new SimpleDateFormat("hh:mm a").parse(o2));
} catch (ParseException e) {
return 0;
}
}
});
System.out.println(l);