简体   繁体   English

如何按年然后按月对日期列表进行分组?

[英]how to group a list of dates by year and then by month?

I need your suggestion in the following scenario 在以下情况下,我需要您的建议

I have the following list of dates 我有以下日期列表

def date = new Date()
def dates = [date - 350, date - 400, date - 300, date - 50, date]

I need to get the following map: 我需要获取以下地图:

[2013:[1:null, 2:5, 3:10,...12:5], 2014:[1:10, 2:30...12:100], ...]

Where year map is: key is month and value is count of dates in that month 年图在哪里:键是月,值是该月的日期计数

I got to group it by year this way 我必须按这种方式按年份分组

def datesGroupedByYear = dates.groupBy { it[Calendar.YEAR] }

How can I create a map as I described 如何按照我的描述创建地图

Thanks for your time 谢谢你的时间

You can add further groups by adding closures to the groupBy call. 您可以通过将闭包添加到groupBy调用中来添加其他组。 Calendar's MONTH is off by one (starts at 0), so add one there. 日历的MONTH减1(从0开始),因此在此加1。 Next you want to fill all month with the count, which is the size() of the group by results. 接下来,您要用计数填充整个月,该计数是结果分组的size()。 This will be collected over 1..12 for each month (proper order and null for the missing groups). 每个月将在1..12以上收集(正确的订单,缺少的组为null )。

def date = new Date()
def dates = [date-350, date-400, date-300, date-50, date-3, date-2, date]

def result = dates.groupBy{it[Calendar.YEAR]}{it[Calendar.MONTH]+1}.collectEntries{ o->
    [o.key, (1..12).collectEntries{
        [it, o.value.get(it)?.size()] 
    }]
}
println result
//; [2013:[1:null, 2:null, 3:null, 4:null, 5:null, 6:null, 7:null, 8:null, 9:null, 10:1, 11:null, 12:1], 2014:[1:1, 2:null, 3:null, 4:null, 5:null, 6:null, 7:null, 8:null, 9:null, 10:1, 11:3, 12:null]]
assert result[date[Calendar.YEAR]][date[Calendar.MONTH]+1]==3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM