从地图的此示例列表中获取
def Assets = [
[year: 2018, valueA:10, value:15],
[year: 2018, valueA:15, value:25],
[year: 2019, valueA:11, value:35],
[year: 2020, valueA:17, value:2],
[year: 2020, valueA:18, value:5],
[year: 2021, valueA:10, value:25],
[year: 2018, valueA:15, value:20]
]
我想创建一个仅包含唯一年份并取均等年份的平均值的汇总列表,以便得出此结果;
SummaryAssets = [
[year: 2018, valueA:13, value:20],
[year: 2019, valueA:11, value:35],
[year: 2020, valueA:18, value:4],
[year: 2021, valueA:10, value:25]
]
我认为这样做的唯一方法是首先找到并创建唯一身份年份列表。然后根据这些年份:
这似乎很麻烦。有更时髦的方法吗? 谢谢。
答案 0 :(得分:0)
我可能会使用groupBy
,但在其他方面与您建议的相同:
def Assets = [
[year: 2018, valueA:10, value:15],
[year: 2018, valueA:15, value:25],
[year: 2019, valueA:11, value:35],
[year: 2020, valueA:17, value:2],
[year: 2020, valueA:18, value:5],
[year: 2021, valueA:10, value:25],
[year: 2018, valueA:15, value:20]
]
def SummaryAssets = Assets.groupBy{ it.year }.collect{
def v = it.value
def avgForKey = { k -> [k, v[k].sum().div(v.size()).round()] }
[year: it.key] + (v*.keySet().sum() - 'year').collectEntries(avgForKey)
}
assert SummaryAssets == [
['year':2018, 'valueA':13, 'value':20],
['year':2019, 'valueA':11, 'value':35],
['year':2020, 'valueA':18, 'value':4],
['year':2021, 'valueA':10, 'value':25]
]