Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I loop through a list and remove an item in groovy?

Tags:

groovy

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)
}
like image 816
ScArcher2 Avatar asked Oct 28 '10 20:10

ScArcher2


People also ask

How do you remove an element from iterable?

An element can be removed from a Collection using the Iterator method remove(). This method removes the current element in the Collection. If the remove() method is not preceded by the next() method, then the exception IllegalStateException is thrown.


2 Answers

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?

like image 116
tim_yates Avatar answered Oct 17 '22 05:10

tim_yates


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]
like image 25
ataylor Avatar answered Oct 17 '22 07:10

ataylor