groovy 如何根据其他值对Map求和

jqjz2hbq  于 12个月前  发布在  其他
关注(0)|答案(3)|浏览(134)

我有一张Map,看起来像:

myMap = [
  [value1: "ABD123", value2: "Robert", value3: 1, value4: "7"],
  [value1: "ABD123", value2: "Robert", value3: 4, value4: "7"],
  [value1: "ABD13a23", value2: "Rob2ert", value3: 1, value4: "7"]
]

字符串
如果其他3个值相同,我想对value3求和。
其输出将是:

myMap = [
  [value1: "ABD123", value2: "Robert", value3: 5, value4: "7"],
  [value1: "ABD13a23", value2: "Rob2ert", value3: 1, value4: "7"]
]

xn1cxnb4

xn1cxnb41#

我的方式:

def myMap = [
  [value1: "ABD123", value2: "Robert", value3: 1, value4: "7"],
  [value1: "ABD123", value2: "Robert", value3: 4, value4: "7"],
  [value1: "ABD13a23", value2: "Rob2ert", value3: 1, value4: "7"]
]

def summed = myMap.groupBy{ it.value1 }.collect{ k, v -> v.first() + [ value3:v*.value3.sum() ] }

assert summed == [
  [
    "value1": "ABD123",
    "value2": "Robert",
    "value3": 5,
    "value4": "7"
  ],
  [
    "value1": "ABD13a23",
    "value2": "Rob2ert",
    "value3": 1,
    "value4": "7"
  ]
]

字符串

wydwbb8l

wydwbb8l2#

锁定10天,目前有disputes about this answer’s content正在解析,目前不接受新的交互。

这应该可以做到:

def myMap = [
  [value1: "ABD123", value2: "Robert", value3: 1, value4: "7"],
  [value1: "ABD123", value2: "Robert", value3: 4, value4: "7"],
  [value1: "ABD13a23", value2: "Rob2ert", value3: 1, value4: "7"]
]

def result = myMap.groupBy {
    // group by everything but value3
    it.subMap(it.keySet() - 'value3')
}.collect { k, v ->
    // and then add value3 back as the sum of all the value3s in the group
    k + [value3: v.value3.sum()]
}

字符串

11dmarpk

11dmarpk3#

有些人更喜欢inject方法,例如:

def myMap = [
        [value1: "Welcome to stackoverflow!", value2: "Now you have 998 ways how to skin a cat left!", value3: 1, value4: "Friday night again!"],
        [value1: "Welcome to stackoverflow!", value2: "Now you have 998 ways how to skin a cat left!", value3: 4, value4: "Friday night again!"],
        [value1: "You really should show what you tried and the issue you're having", value2: "Now you have 997 ways how to skin a cat left!", value3: 1, value4: "Friday night again!"]
]
def result = myMap.inject([:].withDefault {0}) { acc, map ->
    def map2 = map.clone()
    map2.value3 = 0
    acc[map2] += map.value3
    acc
}.collect { k, v -> k.value3 = v; k }

字符串

相关问题