如何在groovy中循环遍历列表并删除项?

如何在groovy中循环遍历列表并删除项?,groovy,Groovy,我试图弄清楚如何从循环中删除groovy列表中的项 static main(args) { def list1 = [1, 2, 3, 4] for(num in list1){ if(num == 2) list1.remove(num) } println(list1) } 我认为你可以做到: list - 2; 或者 不需要循环 如果您想使用循环,我想您可以考虑使用迭代器来实际删除该项 import java.util.Iterator; s

我试图弄清楚如何从循环中删除groovy列表中的项

static main(args) {
   def list1 = [1, 2, 3, 4]
   for(num in list1){
   if(num == 2)
      list1.remove(num)
   }
   println(list1)
}
我认为你可以做到:

list - 2;
或者

不需要循环

如果您想使用循环,我想您可以考虑使用迭代器来实际删除该项

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)
}​
但我不明白你为什么要那样做

list = [1, 2, 3, 4]
newList = list.findAll { it != 2 }
应该给你所有的,除了2


当然,您可能有需要循环的原因?

如果您想删除索引为2的项,您可以这样做

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]
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]
如果要删除值为2的(第一个)项,可以执行以下操作

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]
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]

正如你在评论中所说,你并不特别需要一个循环。。。。如果您愿意修改原始列表,可以使用
removeAll

// Remove all negative numbers
list = [1, 2, -4, 8]
list.removeAll { it < 0 }
//删除所有负数
列表=[1,2,-4,8]
list.removeAll{it<0}

这并不能解释OP(原始海报)所收到的Java的ConcurrentModificationException(关于这个问题最有可能的解决方案是在Java世界中使用CopyOnWriteArrayList),但在我看来,这是Groovy中最实用的方法。-另外,请大家注意,List.remove(int)方法不同于List.remove((Object)int)方法。在groovy中,当您有一个整数列表时,它会调用remove by index。这个示例实际上只是一些真实情况的示例。我最终使用迭代器进行删除,效果非常好。谢谢我只是想澄清一下。我知道我不需要循环,但这演示了我在没有在示例中加入大量额外逻辑的情况下要做的事情。事实上,这并没有真正起作用
i=my.object.here.iterator()
根本无法处理列表。它应该与任何实现
Iterable
接口或具有
iterator()
方法的对象一起工作。