[英]Groovy - Combining a list of Maps into a single Map
I have a list of maps which I am trying to combine into a single map. 我有一张地图清单,试图将它们组合成一张地图。 I've tried using
map.collectEntries()
to do so, but the map that was created contained only the last map from the list. 我尝试使用
map.collectEntries()
这样做,但是创建的地图仅包含列表中的最后一个地图。 My input list is following: 我的输入列表如下:
def people = [[name:'John', age:35], [name:'Jim', age:54]]
I expect to calculate a map like: 我希望计算出像这样的地图:
def people = ['John':35, 'Jim':54]
You have to collect entries from the map with a closure that access name and age 您必须使用访问名称和年龄的闭包从地图中收集条目
def people = [[name:'John', age:35], [name:'Jim', age:54], [name:'Smith', age:'53']]
def nameAgeMap=people.collectEntries() {
[it.name, it.age]
}
println(nameAgeMap)
For simplicity: 为简单起见:
Map<String, String> result = new HashMap<String, String>();
for (Map<String, String> singleMap : people) {
result.putAll(singleMap);
}
Stream API: 流API:
You can do the same using the stream API, which might look for many developers overcomplicated. 您可以使用流API进行相同的操作,这可能会使许多开发人员过于复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.