在 Java 中按时间对 ArrayList 进行排序 [英] Sort ArrayList with times in Java
问题描述
我有一个 List
,其中包含从上午 8:00 到下午 4:00 的时间列表.
I have a List<String>
that contains a list of times from 8:00 am to 4:00 pm.
当我在输出中显示它时,它看起来是未排序的,当我使用 Collections.sort(myList);
时,它会将它排序为从下午 1:00 到上午 8:00.
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.
如何从上午 8:00 到下午 4:00 对我的列表进行排序?
How could I sort my list from 8:00am to 4:00pm ?
推荐答案
不要重新发明轮子,使用集合(或 Lambdas,如果允许 java8)如何??:将列表保留为字符串,但使用匿名比较器,在那里,将字符串解析为日期,将它们进行比较,然后就可以了.这是一个片段:
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<String> l = new ArrayList<String>();
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<String>() {
@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);
这篇关于在 Java 中按时间对 ArrayList 进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!