collections - 在数组列表中收集 findall

标签 collections groovy find

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

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

我需要找到所有年龄或体重在名为 getValidAgeForSchool() 或 getValidWeightForSchool() 的方法返回的有效年龄/体重列表中的人。年龄 [2,3] 或体重 [20,25]

我知道有这样的东西(也不行)

persons.findAll{ it.age == 2 || it.weight == 20}

但我怎么说(比如 IN 子句)

persons.findAll {it.age in [2,3] || it.weight 在 [20,25]} 中。

我也试过这个(暂时忽略重量)但没有在应该返回的时候返回列表 persons.age.findAll{ 它 == 2 ||它 == 3}

谢谢。

最佳答案

你的代码有效:

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 或其他东西?

如果 weight 是 double,您需要这样做:

people.findAll { it.age in [ 2, 3 ] || it.weight in [ 20d, 25d ] }.id

但是小心,这是在做双重等式比较,所以如果你对权重做任何算术,你可能会成为舍入和准确性错误的牺牲品

关于collections - 在数组列表中收集 findall,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19791756/

相关文章:

java - 如何将 HashMap 显示为空 {} 而不是 null

java - 根据其键的子集过滤 map 的元素,而无需遍历整个事物

Grails Eclipse 插件

相当于 find2perl 的 Python

linux - 在 Linux 中为每个文件查找和 tar

java - 为什么 HashMap<String, Object> 不接受 HashMap<String, List> 实例?

java - 检查数组的值

rest - Jenkins : execute HTTP request without 3rd party libraries 的 Groovy 脚本

java - Apache Camel 抛出 java.lang.NoSuchMethodError : org. apache.camel.util.ObjectHelper.notNull

linux - 从查找中排除特定文件