How do I loop through a list and remove an item in groovy?
I'm tryi开发者_如何学JAVAng 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)
}
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?
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]
As you state in your comment that you do not specifically require a loop .... If you are happy to modify your original list you can use removeAll
:
// Remove all negative numbers
list = [1, 2, -4, 8]
list.removeAll { it < 0 }
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.
精彩评论