如何按升序对包含星期几名称的字符串进行排序 [英] How to sort strings containing day-of-week names in ascending order

查看:23
本文介绍了如何按升序对包含星期几名称的字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含星期名称、开始时间和结束时间的字符串列表:

I have a list of Strings containing Day-of-week name, start time and End time:

List<String> eventList = Database.getEventsForThisWeek();

示例数据:

Thursday (13:00 to 14:30)
Saturday (14:20 to 18:10)
Monday (09:00 to 14:25)
Saturday (11:00 to 12:30)

我想对列表进行排序,以便星期几按升序排列.如果有多个记录的星期几相同,那么开始时间也应该按升序排列.

I want to sort the List such a way so that the Day-of-week is in ascending order. and if there are multiple records with the same day-of-week, then the Start time should be in ascending order too.

例如,排序后,上面的列表应该是这样的:

For example, after sorting, the above list should look like:

Monday (09:00 to 14:25)    
Thursday (13:00 to 14:30)
Saturday (11:00 to 12:30)
Saturday (14:20 to 18:10)

对列表进行排序的最佳方法是什么?

What is the best way to sort the List ?

推荐答案

给你:

List<String> dates = Arrays.asList(new String[]{
        "Thursday (13:00 to 14:30)",
        "Saturday (14:20 to 18:10)",
        "Monday (09:00 to 14:25)",
        "Saturday (11:00 to 12:30)"
});
Comparator<String> dateComparator = new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        try{
            SimpleDateFormat format = new SimpleDateFormat("EEE");
            Date d1 = format.parse(s1);
            Date d2 = format.parse(s2);
            if(d1.equals(d2)){
                return s1.substring(s1.indexOf(" ") + 1).compareTo(s2.substring(s2.indexOf(" ") + 1));
            }else{
                Calendar cal1 = Calendar.getInstance();
                Calendar cal2 = Calendar.getInstance();
                cal1.setTime(d1);
                cal2.setTime(d2);
                return cal1.get(Calendar.DAY_OF_WEEK) - cal2.get(Calendar.DAY_OF_WEEK);
            }
        }catch(ParseException pe){
            throw new RuntimeException(pe);
        }
    }
};
Collections.sort(dates, dateComparator);
System.out.println(dates);

这篇关于如何按升序对包含星期几名称的字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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