2014-11-21 160 views
1

我正在學習Groovy,並且正在嘗試編寫以下Java代碼的替代方案。使用findAll方法Groovy過濾數組

Collection<Record> records = requestHelper.getUnmatchedRecords(); 
Collection<Integer> recordIdentifiers = new ArrayList<>(); 
for (Record record : records){ 
    int rowId = record.getValue("RowID"); 
    if (rowId >= min && rowId <= max) { 
     recordIdentifiers.add(rowId); 
    } 
} 

當這段代碼運行時recordIdentifiers應該包含50個項目。這是迄今爲止我的Groovy等價物。

def records = requestHelper.getUnmatchedRecords() 
def recordIdentifiers = records.findAll{record -> 
    int rowId = record.getValue("RowId") 
    rowId >= min && rowId <= max 
} 

由於某些原因,在Groovy代碼執行後數組包含100個項目。所有findAll()的例子都是在Groovy中本地構建數組時進行的簡單比較,但是如何過濾從Java類接收的Collection?

+0

什麼是100和50在這裏? 'records'中有多少個?過濾器是不是工作或在'recordIdentifiers'中有重複?乍一看,代碼看起來不錯。 – cfrick 2014-11-21 09:59:27

+1

正如我後來發現的,我的代碼很好,但我們的一個初級開發人員生成了一個錯誤的數據集供我使用 - 它有重複的,因此而不是50個記錄,我有100個。他現在已經感到羞愧。 – user283188 2014-11-21 14:59:34

回答

2

似乎很奇怪。以下代碼正常工作:

def records = [[r:3],[r:5],[r:6],[r:11],[r:10]] 
def range = (1..10) 
recordIdentifiers = records.findAll { range.contains(it.r) } 
assert recordIdentifiers.size() == 4 

請您提供一個工作示例?