从Map获取列表并使用groovy过滤
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从Map获取列表并使用groovy过滤相关的知识,希望对你有一定的参考价值。
我试图从地图中获取一个列表并基于id的列表,并希望根据年龄(年龄> 35)检索值(列表)
def people = [
"1": [[name:'Bob', age: 32, gender: 'M'],[name:'Johnny', age: 36, gender: 'M']],
"3": [[name:'Claire', age: 21, gender: 'F'],[name:'Amy', age: 54, gender:'F']],
"4": [[name:'John', age: 41, gender: 'F'],[name:'Sam', age: 54, gender:'F']]
]
def id = ["1","3"]
def age = people.subMap(id).values().findAll{it.age > 35}
但是,我收到以下错误:
Cannot compare java.util.ArrayList with value '[32, 36]' and java.lang.Integer with value '35'
如何获得年龄> 35岁的所有人的名单?
答案
你需要.flatten()
people.subMap(id).values()
的结果,因为它产生一个地图列表列表:
[[[name:Bob, age:32, gender:M], [name:Johnny, age:36, gender:M]], [[name:Claire, age:21, gender:F], [name:Amy, age:54, gender:F]]]
当你做people.subMap(id).values().flatten()
时,你会得到一张地图列表:
[[name:Bob, age:32, gender:M], [name:Johnny, age:36, gender:M], [name:Claire, age:21, gender:F], [name:Amy, age:54, gender:F]]
然后你可以申请.findAll { it.age > 35 }
def people = [
"1": [[name: 'Bob', age: 32, gender: 'M'], [name: 'Johnny', age: 36, gender: 'M']],
"3": [[name: 'Claire', age: 21, gender: 'F'], [name: 'Amy', age: 54, gender: 'F']],
"4": [[name: 'John', age: 41, gender: 'F'], [name: 'Sam', age: 54, gender: 'F']]
]
def id = ["1", "3"]
def age = people.subMap(id).values().flatten().findAll { it.age > 35 }
println age
输出:
[[name:Johnny, age:36, gender:M], [name:Amy, age:54, gender:F]]
希望能帮助到你。
另一答案
虽然不像其他答案那样Groovy,但一个简单的方法是通过变换函数对collect
进行处理,并返回[]
进行不匹配(可以是flattened
)。
就是这样:
def people = [
"1": [[name:'Bob', age: 32, gender: 'M'],[name:'Johnny', age: 36, gender: 'M']],
"3": [[name:'Claire', age: 21, gender: 'F'],[name:'Amy', age: 54, gender:'F']],
"4": [[name:'John', age: 41, gender: 'F'],[name:'Sam', age: 54, gender:'F']]
]
def targetIds = ["1","3"]
def targetAge = 35
然后:
def findAgeOverN = { def key, def list, def ids, def n ->
(ids.contains(key)) ? list.findAll { it["age"] > n } : []
}
def result = people.collect { key, list -> findAgeOverN(key, list, targetIds, targetAge) }
.flatten()
assert [[name:'Johnny', age: 36, gender: 'M'],
[name:'Amy', age: 54, gender: 'F']]
以上是关于从Map获取列表并使用groovy过滤的主要内容,如果未能解决你的问题,请参考以下文章
Groovy - 如何在不更新地图的情况下使用默认值获取地图值
使用 Groovy(Grails) 写入文件对于某些行(断行)失败
在 Groovy 上使用 JSON 响应并使用响应填充 Map