在Java中按时间对ArrayList进行排序 [英] Sort ArrayList with times in Java

查看:265
本文介绍了在Java中按时间对ArrayList进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表< String> ,其中包含从上午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: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点到下午4点对列表进行排序?

How could I sort my list from 8:00am to 4:00pm ?

推荐答案

不要重新发明轮子,使用集合(或者如果允许java8则使用Lambda)
如何??:
将列表保留为字符串,但使用Anonymous 比较器,在那里,将字符串解析为日期,比较它们,你有它。
这里是一个片段:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆