[SalesForce] remove element from a list being looped through

In apex, how can I remove an element from a list being looped?

List<String> companyinfos=new List<String>();
companyinfos.add('a1');
companyinfos.add('a2');
companyinfos.add('a3');
companyinfos.add('b1');
companyinfos.add('b2');

integer index=0;
For(String s: companyinfos)
{
    if(s.contains('a')){
        companyinfos.remove(index);
        index--;
    }
index++;
}  


System.debug(companyinfos);  

ERROR:
Cannot modify a collection while it is being iterated.

Best Answer

As long as you don't use the shorthand iteration technique for(Object a : Objects) and use a traditional for loop, it works fine (you must traverse the list in reverse order - thanks Willem)

Try this:

for (Integer i = (companyinfos.size()-1) ; i>= 0 ; i--){
    String s = companyInfos[i];
    if(s.contains('a')){
        companyinfos.remove(i);
    }
} 
Related Topic