2015-10-13 38 views
0

我有一個Person對象(person.first person.last)的數組。groovy&grails-如何去數組對象?

要了解該人是否有名字,我必須「在陣列上運行」。

我嘗試以下方法,但我得到的錯誤:

person.eachWithIndex { String persons, i -> 
if(persons.first=='') 
println(''error) 
} 

我應該如何操作對象數組?

+0

http://docs.groovy-lang.org/latest/html/documentation/index.html#_looping_structures – cfrick

回答

0

你是否在尋找類似:

class Person { 
    def first 
    def last 
} 

def persons = [ new Person(first:'',last:'last'), new Person(first:'john',last:'anon')] 

persons.eachWithIndex { person, i -> 
    if(person.first==''){ 
     println("error at person in position $i") 
    } 
} 

既然你不添加更多的細節,我不知道你在找什麼,當你說操縱對象數組所以對於一些樣本:

要操作的數組對象,您可以添加在each本身的語句,例如爲notDefined添加爲first的人在那裏first==''你可以使用:

persons.eachWithIndex { person, i -> 
    if(person.first==''){ 
     person.first = 'notDefined' 
     println("first as notDefined for person in position $i") 
    } 
} 

爲了除去其中first ==''可以使用removeAll方法以除去從數組中不期望的元素中的元素:

persons.removeAll { person -> 
    !person.first 
} 

EDIT基於COMMENT:

如果要刪除null元素從您的列表中,您可以使用您在評論中使用的表達方式:

def persons = [ new Person(first:'pepe',last:'last'), null] 
persons.removeAll([null]) 
println persons.size() // prints 1 since null element is removed 

但是,似乎您並未試圖刪除空元素,而是嘗試刪除所有屬性均爲空的元素,而您的情況則是要刪除:new Person(first:null,last:null)。要做到這一點,你可以用如下的代碼嘗試:

def persons = [ new Person(first:'pepe',last:'last'), new Person(first:null,last:null)] 

persons.removeAll{ person -> 
    // get all Person properties wich value is not null 
    // without considering class propertie wich is implicit in all classes 
    def propsNotNull = person.properties.findAll { k,v -> v != null && k != 'class' } 
    // if list is empty... means that all properties are null 
    return propsNotNull.isEmpty() 
} 

println persons.size() // prints 1 

希望這有助於

+0

@ albciff-如果我有其所有屬性爲空的對象。我怎樣才能刪除它們? –

+0

我試過invitation.removeAll([null]),但它不起作用 –

+0

@SaritRotshild我更新了我的迴應':)' – albciff