list.groupBy()的问题

pri*_*dev 1 collections groovy

我有一个列表如下

def qresultList = [
    [location: 'a', txs: 10],
    [location: 'b', txs: 20],
    [location: 'a', txs: 30]
]
Run Code Online (Sandbox Code Playgroud)

我希望得到相同位置的txs总和的不同位置列表..所以我在这样的位置上做groupby:

def totalsByLocation1 = qresultList.groupBy{ it.location }.
    collectEntries{ key, vals -> [key, vals*.txs.sum()] }
Run Code Online (Sandbox Code Playgroud)

上面的代码在SummaryUtilsService/getWorldSummary函数内部
我收到以下错误

No signature of method: java.util.LinkedHashMap.collectEntries() is applicable for argument types: (summary.SummaryUtilsService$_getWorldSummary_closure3) values: [summary.SummaryUtilsService$_getWorldSummary_closure3@2750e6c9]
Run Code Online (Sandbox Code Playgroud)

更新:查询的实际结果是

def qresultList =  [
        ['a', 10],
        ['b', 20],
        ['a', 30]
    ]
Run Code Online (Sandbox Code Playgroud)

所以列表清单..

tim*_*tes 5

从早期的问题来看,我假设您使用的是Grails 1.3.7或其他东西

pre-groovy 1.8.X这样做的方法是:

def totalsByLocation1 = qresultList.groupBy{ it.location }.inject([:]) { map, val ->
  map << [ (val.key): val.value*.txs.sum() ]
}
Run Code Online (Sandbox Code Playgroud)

编辑

如果您的输入列表是:

def qresultList =  [
  ['a', 10],
  ['b', 20],
  ['a', 30]
]
Run Code Online (Sandbox Code Playgroud)

然后你需要这样的东西:

qresultList.groupBy { it[ 0 ] }.collectEntries { k, v ->
  [ (k): v*.getAt( 1 ).sum() ]
}
Run Code Online (Sandbox Code Playgroud)