作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
问题:
我有一大堆日期,我需要按周排列它们。
问题:如何按日期所在的一年中的第几周对日期进行分组?
示例数据集
Date date = new SimpleDateFormat.parse("04/01/2015")
Date date = new SimpleDateFormat.parse("04/02/2015")
Date date = new SimpleDateFormat.parse("04/03/2015")
Date date = new SimpleDateFormat.parse("04/04/2015")
Date date = new SimpleDateFormat.parse("04/05/2015")
Date date = new SimpleDateFormat.parse("04/06/2015")
Date date = new SimpleDateFormat.parse("04/07/2015")
Date date = new SimpleDateFormat.parse("04/08/2015")
Date date = new SimpleDateFormat.parse("04/09/2015")
期望的输出
HashMap<Date, Date> hashMap = groupByWeek(ArrayList<Date> dates);
printWeeklyGroupedDates();
Week 1:
04/01/2015
04/02/2015
04/03/2015
04/04/2015
04/05/2015
04/06/2015
04/07/2015
Week 2:
04/08/2015
04/09/2015
我尝试过的
public Date getWhichYearlyWeek(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.get(Calendear.WEEK_OF_YEAR);
//Need to return this as 'Date' but indicate which week this is for the TreeMap functionality below
return cal.getTime();
}
public TreeMap<Date, ArrayList<Date>> getWeeklyMappedDates(ArrayList<Date> dateArray){
TreeMap<Date, ArrayList<Date>> treeMap = new TreeMap<Date, ArrayList<Date>>
for(Date i : dateArray){
Date date = getWhichYearlyWeek(date);
if(!treeMap.containsKey(date))
treeMap.get(date).add(date);
else
treeMap.put(date, new ArrayList<Date>());
}
return treeMap;
}
最佳答案
如果 Java 8 可用:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
TemporalField weekOfYear = WeekFields.of(Locale.getDefault()).weekOfYear();
Stream.of(
"04/01/2015"
, "04/02/2015"
, "04/03/2015"
, "04/04/2015"
, "04/05/2015"
, "04/06/2015"
, "04/07/2015"
, "04/08/2015"
, "04/09/2015"
)
.collect(Collectors.groupingBy(
d -> LocalDate.parse(d, formatter).get(weekOfYear),
LinkedHashMap::new,
Collectors.toList()
))
.forEach((week, dates) -> {
System.out.println("Week " + week + ":");
dates.forEach(System.out::println);
});
这会打印(在我的计算机上使用 de_CH
语言环境)
Week 14:
04/01/2015
04/02/2015
04/03/2015
04/04/2015
04/05/2015
Week 15:
04/06/2015
04/07/2015
04/08/2015
04/09/2015
关于Java : How do I group all java Dates in their corresponding week?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29953862/
我是一名优秀的程序员,十分优秀!