groovy 相似键值对的求和值

z31licg0  于 2023-11-16  发布在  其他
关注(0)|答案(1)|浏览(114)

我有一个对象数组

[
  {
    id: '1109',
    year: 2022,
    amount: 558270
  },
  {
    id: '1109',
    year: 2022,
    amount: 22842680
  },
  {
    id: '1109',
    year: 2021,
    amount: 32342
  },
  {
    id: '1109',
    year: 2020,
    amount: 323111
  }
],
[
  {
    id: '197',
    year: 2019,
    amount: 9000
  },
  {
    id: '197',
    year: 2023,
    amount: 3000
  },
  {
    id: '197',
    year: 2019,
    amount: 2000
  },
  {
    id: '197',
    year: 2020,
    amount: 1000
  }
]

字符串
我尝试做的是添加相同yearamount,并将它们添加到新的year中。
我现在做的哪些是

def newVal = [:]
def arr = []
for(int ii=0 ; ii< arr.size(); ii++){
          for(int jj=1 ; jj < arr.size(); jj++){
              if(arr[ii].year == arr[jj].year){
                  newVal.put("id", arr[i].id)
                  newVal.put("year", arr[ii].year)
                  newVal.put("amount", arr[ii].amount + arr[jj].amount)
                  arr.add(newVal)
              }
          }
      }


这是我的输出

[
  { id: '1109', year: 2022, amount: 23400950 },
  { id: '1109', year: 2022, amount: 45685360 },
  { id: '1109', year: 2021, amount: 64684 },
  { id: '1109', year: 2020, amount: 646222 }
]
[
  { id: '197', year: 2019, amount: 11000 },
  { id: '197', year: 2023, amount: 6000 },
  { id: '197', year: 2019, amount: 4000 },
  { id: '197', year: 2020, amount: 2000 }
]


期望输出

[
  {
    id: '1109',
    year: 2022,
    amount: 23400950
  },
  {
    id: '1109',
    year: 2021,
    amount: 32342
  },
  {
    id: '1109',
    year: 2020,
    amount: 323111
  }
],
[
  {
    id: '197',
    year: 2019,
    amount: 11000
  },
  {
    id: '197',
    year: 2023,
    amount: 3000
  },
  {
    id: '197',
    year: 2020,
    amount: 1000
  }
]

q43xntqr

q43xntqr1#

不确定您看到的问题是什么,但是如果您有您的问题中描述的输入(但是是Groovy可以解析的格式)

def input = [
        [
                [id: '1109', year: 2022, amount: 558270],
                [id: '1109', year: 2022, amount: 22842680],
                [id: '1109', year: 2021, amount: 32342],
                [id: '1109', year: 2020, amount: 323111]
        ],
        [
                [id: '197', year: 2019, amount: 9000],
                [id: '197', year: 2023, amount: 3000],
                [id: '197', year: 2019, amount: 2000],
                [id: '197', year: 2020, amount: 1000]
        ]
]

字符串
然后你可以这样做:

def result = input.collect {
    it.groupBy { it.year }
      .collect { year, entries ->
          [year: year, id: entries.id[0], amount: entries.amount.sum()]
      }
}


result等于:

[
  [
    [year:2022, id:1109, amount:23400950],
    [year:2021, id:1109, amount:32342],
    [year:2020, id:1109, amount:323111]
  ],
  [
    [year:2019, id:197, amount:11000],
    [year:2023, id:197, amount:3000],
    [year:2020, id:197, amount:1000]
  ]
]


我相信这就是你想要的

相关问题