在groovy中从列表创建地图的快捷方式? [英] shortcut for creating a Map from a List in groovy?
问题描述
映射rowToMap(row){
def rowMap = [ :];
row.columns.each {rowMap [it.name] = it.val}
return rowMap;
}
给出GDK的东西,我希望能够做类似于:
映射rowToMap(row){
row.columns.collectMap {[it.name,it .val]}
}
但我在文档中没有看到任何东西。 。我错过了什么?
我最近遇到了需要做的事情:将列表转换为一张地图。这个问题发布在Groovy版本1.7.9之前,所以方法 collectEntries
尚不存在。它的工作原理与 collectMap
方法 :
映射rowToMap
row.columns.collectEntries {[it.name,it.val]}
}
$ b b
如果由于某种原因,您使用的是旧版本的Groovy,则 inject
方法(如在这里)。这是一个稍微修改的版本,只在闭包内只有一个表达式(只是为了节省字符!):
rowToMap(row){
row.columns.inject([:]){map,col - > map<< [(col.name):col.val]}
}
也可以使用$ c> + 运算符代替<<
。
I'd like some sorthand for this:
Map rowToMap(row) {
def rowMap = [:];
row.columns.each{ rowMap[it.name] = it.val }
return rowMap;
}
given the way the GDK stuff is, I'd expect to be able to do something like:
Map rowToMap(row) {
row.columns.collectMap{ [it.name,it.val] }
}
but I haven't seen anything in the docs... am I missing something? or am I just way too lazy?
I've recently came across the need to do exactly that: converting a list into a map. This question was posted before Groovy version 1.7.9 came out, so the method collectEntries
didn't exist yet. It works exactly as the collectMap
method that was proposed:
Map rowToMap(row) {
row.columns.collectEntries{[it.name, it.val]}
}
If for some reason you are stuck with an older Groovy version, the inject
method can also be used (as proposed here). This is a slightly modified version that takes only one expression inside the closure (just for the sake of character saving!):
Map rowToMap(row) {
row.columns.inject([:]) {map, col -> map << [(col.name): col.val]}
}
The +
operator can also be used instead of the <<
.
这篇关于在groovy中从列表创建地图的快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!