【发布时间】:2015-09-24 02:40:17
【问题描述】:
我在 Java 中有一个包含一组随机日期的数组:
{ 2015 年 1 月 20 日、2015 年 2 月 12 日、2015 年 2 月 20 日、2015 年 6 月 21 日、 2015 年 7 月 12 日、2015 年 7 月 28 日、2015 年 7 月 30 日、2015 年 9 月 24 日、2015 年 12 月 31 日}
如何将这个数组按月拆分成多个数组?
我想要
{ {2015 年 1 月 20 日}、{2015 年 2 月 12 日、2015 年 2 月 20 日}、{2015 年 6 月 21 日}、 {2015 年 7 月 12 日、2015 年 7 月 28 日、2015 年 7 月 30 日}、{2015 年 9 月 24 日}、{2015 年 12 月 31 日}}
我可以遍历整个数组并检查下一个日期是否仍在同一个月内,如果是,则将其添加到子数组中。但是我想知道是否有更简洁或更有效的方法。
编辑:
此外,我需要按年和月排序,例如,2014 年 1 月 15 日和 2015 年 1 月 23 日不应合并。
这是我想出的一个方法,但看起来效率不高:
private void splitListByMonth(){
ArrayList<ArrayList<Homework>> mainArrayList = new ArrayList<>();
ArrayList<String> titleList = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM yyy");
for(Homework homework:mList){
calendar.setTimeInMillis(homework.getDate());
String monthString = dateFormat.format(calendar.getTime());
if(titleList.contains(monthString)){
int index = titleList.indexOf(monthString);
mainArrayList.get(index).add(homework);
} else {
titleList.add(monthString);
int index = titleList.indexOf(monthString);
mainArrayList.get(index).add(homework);
}
}
Log.d("Tag",""+titleList);
Log.d("Tag",""+mainArrayList);
}
【问题讨论】:
-
仅按月还是按年/月?例如。
Jan 15 2014和Jan 23 2015是否应该合并?数组是否总是排序的,或者日期可以是随机顺序吗? -
也许你应该使用
> 的地图。认为它会更好地为您服务。 -
为什么不只是使用像
List<List<Dates>>这样的列表列表,每个月从 0 到 11 将对应于适当的索引,即所有 1 月份的日期都在索引 0 中。 -
是的,我同意,使用
List<List<Dates>>将大大解决问题 -
@WayWay 请通过编辑您的问题而不是作为 cmets 发布来发布更多信息/说明。