2012-01-10 62 views
13

是否有Groovy在迭代時刪除集合項目的方法?在Java中,這是使用Iterator.remove()完成:Groovy在迭代時刪除集合項目

Collection collection = ... 
for (Iterator it=collection.iterator(); it.hasNext();) { 
    Object obj = it.next(); 
    if (should remove) { 
     it.remove(); 
    } 
} 

確實的Groovy提供刪除,同時,迭代在其語言的語法,或者我已經不使用Iterator.remove()

回答

23

Use removeAll()

> c = [1, 2, 3, 4, 5] 
> c.removeAll { it % 2 == 0 } 
> println c 
[1, 3, 5] 

你問具體關於「while iterating」,你是否試圖用/每個對象做什麼? removeAll仍然有效,只要關閉的最後一句話仍然是truthy/falsey(如前):

> c.removeAll { 
*  tmp = it * 10 
*  println "ohai ${it}*10=${tmp}" 
*  tmp >= 40 
* } 
ohai 1*10=10 
ohai 2*20=20 
ohai 3*30=30 
ohai 4*40=40 
ohai 5*50=50 
> println c 
[1, 2, 3] 

封閉的返回值(最後陳述或明確return值的值)爲truthy/falsey,它將用於確定應該刪除的內容。它不需要明確提及每個對象。

+2

非常酷!我不知道.removeAll {} – 2012-01-10 18:37:08

+1

@JarredOlson如果您是Groovy的新手,我建議您避免使用基於手動迭代器的循環(或for for()for循環)。使用基於閉包的方法,如'each','collect','findAll'等我從來沒有必要在Groovy中使用顯式迭代器,這已經是一個很大的緩解= D – epidemian 2012-01-10 19:43:30

+0

@epidemian我不是新的,只是不知道.removeAll {},我只是覺得它很酷:)我會迴應你的聲明,儘管使用Collection上的方法是熟悉閉包/ Groovy的非常好的方法。 – 2012-01-10 19:49:23