gpt4 book ai didi

Java : How do I group all java Dates in their corresponding week?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:48:47 27 4
gpt4 key购买 nike

问题:

我有一大堆日期,我需要按周排列它们。

问题:如何按日期所在的一年中的第几周对日期进行分组?

示例数据集

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com