我有一个字符串列表,其中包含星期名称,开始时间和结束时间:
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)
我想对列表进行排序,以便星期几按升序排列。如果有多个记录具有相同的星期几,则开始时间也应按升序排列。
例如,排序后,上面的列表应如下所示:
Monday (09:00 to 14:25)
Thursday (13:00 to 14:30)
Saturday (11:00 to 12:30)
Saturday (14:20 to 18:10)
对List进行排序的最佳方法是什么?
答案 0 :(得分:4)
你走了:
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);