我正在使用groovy并且我有一个集合:
我需要通过名为getValidAgeForSchool()或getValidWeightForSchool()ex的方法找到年龄或体重在有效年龄/体重列表中的所有人。年龄[2,3]或体重[20,25]
我知道有类似的东西(不能正常工作)
persons.findAll{ it.age == 2 || it.weight == 20}
但我怎么说(如IN条款)
persons.findAll {it.age in [2,3] || it.weight in [20,25]}
。
我也尝试了这个(暂时忽略了重量),但是在它应该的时候没有返回列表
persons.age.findAll{ it == 2 || it == 3}
感谢。
答案 0 :(得分:9)
您所使用的代码:
def people = [
[ id: 1, age: 1, weight: 25 ],
[ id: 2, age: 2, weight: 20 ],
[ id: 3, age: 3, weight: 25 ]
]
// This will find everyone (as everyone matches your criteria)
assert people.findAll {
it.age in [ 2, 3 ] || it.weight in [ 20, 25 ]
}.id == [ 1, 2, 3 ]
如果你有一个像这样的实例列表,它也有效:
class Person {
int id
int age
int weight
}
def people = [
new Person( id: 1, age: 1, weight: 25 ),
new Person( id: 2, age: 2, weight: 20 ),
new Person( id: 3, age: 3, weight: 25 )
]
我假设你的问题是你有weight
作为双重或什么?
如果体重是double
,则需要执行以下操作:
people.findAll { it.age in [ 2, 3 ] || it.weight in [ 20d, 25d ] }.id
但要注意,这是进行双重等式比较,所以如果你对权重进行任何算术运算,你可能会成为舍入和准确性错误的牺牲品