tags:

views:

64

answers:

3

I'm trying to figure out how to remove an item from a list in groovy from within a loop.

static main(args) {
   def list1 = [1, 2, 3, 4]
   for(num in list1){
   if(num == 2)
      list1.remove(num)
   }
   println(list1)
}
+1  A: 

I think you can do:

list - 2;

or...

list.remove(2)

There's no loop required.

If you want to use a loop I guess you could look at using the iterator to actually remove the item.

import java.util.Iterator;

static main(args) {   def list1 = [1, 2, 3, 4]
   Iterator i = list1.iterator();
   while (i.hasNext()) {
      n = i.next();
      if (n == 2) i.remove();
   }
   println(list1)
}​

but I don't see why you'd want to do it that way.

Jon
The example was really meant to only be an example of some real world situation. I ended up using the iterator to do the remove and it worked great. Thanks!
ScArcher2
+1  A: 
list = [1, 2, 3, 4]
newList = list.findAll { it != 2 }

Should give you all but the 2

Of course you may have a reason for requiring the loop?

tim_yates
That doesn't explain Java's ConcurrentModificationException that the OP (original poster) had received (the most likely solution on that issue would be to use a CopyOnWriteArrayList in the Java world), but, in my eyes, this is the most practical way in Groovy. - Please, may, additionally, everyone note that the List.remove(int) method differs from the List.remove((Object) int) method.
robbbert
In groovy it calls remove by index when you have a list of integers.
ScArcher2
+1  A: 

If you want to remove the item with index 2, you can do

list = [1,2,3,4]
list.remove(2)
assert list == [1,2,4]

// or with a loop
list = [1,2,3,4]
i = list.iterator()
2.times {
    i.next()
}
i.remove()
assert list == [1,2,4]

If you want to remove the (first) item with value 2, you can do

list = [1,2,3,4]
list.remove(list.indexOf(2))
assert list == [1,3,4]

// or with a loop
list = [1,2,3,4]
i = list.iterator()
while (i.hasNext()) {
    if (i.next() == 2) {
        i.remove()
        break
    }
}
assert list == [1,3,4]
ataylor