集合列表中的集合findall

use*_*102 3 collections groovy find

我正在使用groovy,我有一个集合:

  • 1号人:年龄1岁,体重25岁
  • 人2:年龄-2岁,体重20岁
  • 人3:年龄-3岁,体重 - 25岁

我需要通过一个名为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}

谢谢.

tim*_*tes 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 ]
Run Code Online (Sandbox Code Playgroud)

如果你有一个像这样的实例列表,它也可以工作:

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 )
]
Run Code Online (Sandbox Code Playgroud)

我假设你的问题是你有weight双重或什么?

如果体重是a double,你需要做:

people.findAll { it.age in [ 2, 3 ] || it.weight in [ 20d, 25d ] }.id
Run Code Online (Sandbox Code Playgroud)

要注意,这是进行双重等式比较,所以如果你对重量进行任何算术运算,你可能会成为舍入和精度误差的牺牲品