从groovy中的列表创建地图的快捷方式? [英] shortcut for creating a Map from a List in groovy?

查看:14
本文介绍了从groovy中的列表创建地图的快捷方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一些帮手:

Map rowToMap(row) {
    def rowMap = [:];
    row.columns.each{ rowMap[it.name] = it.val }
    return rowMap;
}

考虑到 GDK 的内容,我希望能够执行以下操作:

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?

推荐答案

我最近遇到了需要做的事情:将列表转换为地图.这个问题是在 Groovy 1.7.9 版本出来之前贴出来的,所以方法 collectEntries 尚不存在.它与 collectMap 方法完全一样工作 提议的:

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

如果由于某种原因您坚持使用较旧的 Groovy 版本,inject 方法也可以使用(如建议的此处).这是一个稍微修改的版本,在闭包中只需要一个表达式(只是为了字符保存!):

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆