-4

I had a foreach loop that iterates through an arraylist.

In the body of the for loop I have an if condition which removes the current item from the list.

for (item in mylist){
    if(some condition is met)
        mylist.remove(mylist.indexOf(item))
}

But this is causing a java.util.ConcurrentModificationException to be thrown, is it illegal to do this in groovy, and if so how can i get past this?

tim_yates
  • 167,322
  • 27
  • 342
  • 338
robel
  • 305
  • 3
  • 14
  • 1
    Next time: do prior research. It always surprises me how many folks assume that they are the first person to run into such problems ... – GhostCat Apr 19 '16 at 13:34

2 Answers2

0

Removing while iterating over a list can easily be achieved using Iterators.

I'll provide a small (self-explanatory) example here:

List<String> foo = new ArrayList<String>();
// fill foo with data
Iterator<String> it = foo.iterator();
while (it.hasNext()) {
    String s = it.next();
    if (s.equals("B"))
        foo.remove("B");
}
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
0

If you don't mind creating a new List (rather than modifying the original), then a fairly idiomatic approach would be:

mylist = mylist.findAll{ !some condition is met }

Otherwise, if you want to modify the collection you can use the removeAll/retainAll methods and just use:

mylist.removeAll{ some condition is met }
rhinds
  • 9,976
  • 13
  • 68
  • 111
  • Ahh, the rollercoaster ride of stackoverflow voting :) - anyone care to elaborate on downvotes? – rhinds Apr 19 '16 at 14:04
  • Guessing it's java people as this question was mis-tagged. `findAll` is the idiomatic groovy solution – tim_yates Apr 19 '16 at 16:13
  • Ahh right - I was going to comment on the OP as they do specifically ask if it allowed in groovy, and the linked duplicate question is all java, but didn't want to incur the wrath of the SO masses! – rhinds Apr 19 '16 at 16:52