java对arraylist排序,在Java中按时间对ArrayList进行排序

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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值