2016-01-06 61 views
0

我已經陣列在常規的Groovy的findAll在陣列

def userList = [[name: user1, id:0, ip: 127.0.0.1], [name: user2, id:1, ip: 127.0.0.2], [name: user3, id:2, ip: 127.0.0.3]] 

以下數組我遍歷另一個列表rows的陣列和我想從基於索引上面的列表中提取的條目。

rows.eachWithIndex { row, index -> 
     groovy.lang.Closure idMatch = { it.id == index } 
     def match = userList.findAll(idMatch) 
     println(match) 
    } 

匹配總是返回空。

當我打印它時,索引值正確顯示爲0,1,2等。

+0

您的代碼對我的作品...... –

+2

我的猜測是,'你id'' userList'不是'Integer' –

+0

@tim_yates是否必須使用'it.id.toInteger()'? – user2133404

回答

2

使用Groovy 2.4及以上,一個辦法是在rows而不是eachWithIndex使用indicescollect():在

def userList = [ 
    [name: 'user1', id:0, ip: '127.0.0.1'], 
    [name: 'user2', id:1, ip: '127.0.0.2'], 
    [name: 'user3', id:2, ip: '127.0.0.3'] 
] 

def rows = ['foo', 'bar'] 

// Using indices 
rows.indices.collect { index -> 
    userList.find { it.id == index } 
} 

// Using indexed()  
rows.indexed().collect { index, item -> 
    userList.find { it.id == index } 
} 
+0

indexed()方法或索引看起來不可用。 'rows'是一個列表,我正在使用grails 2.4.4 – user2133404

+0

有意義的是,Grails 2.4.4隨Groovy 2.3.7一起提供。 – dmahapatro

+1

由於您有問題,應該打印預期結果。匹配打印結果。 @ user2133404 – dmahapatro