在Groovy中创建地图摘要列表

时间:2018-10-21 01:45:11

标签: arrays groovy

从地图的此示例列表中获取

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]
]

我认为这样做的唯一方法是首先找到并创建唯一身份年份列表。然后根据这些年份:

  1. 计算每个唯一年份的实例数
  2. 一年中每个实例的总和A
  3. 一年中每个实例的总值B
  4. 将每个总数除以重复实例数
  5. 将结果写入新的SummaryAssets列表

这似乎很麻烦。有更时髦的方法吗? 谢谢。

1 个答案:

答案 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]
]