Delete data from ArrayList with a For-loop

The Problem here is you are iterating from 0 to size and inside the loop you are deleting items. Deleting the items will reduce the size of the list which will fail when you try to access the indexes which are greater than the effective size(the size after the deleted items).

There are two approaches to do this.

Delete using iterator if you do not want to deal with index.

for (Iterator<Object> it = data.iterator(); it.hasNext();) {
if (it.next().getCaption().contains("_Hardi")) {
    it.remove();
}
}

Else, delete from the end.

for (int i = size-1; i >= 0; i--){
    if (data.get(i).getCaption().contains("_Hardi")){
            data.remove(i);
    }
 }

Every time you remove an item, you are changing the index of the one in front of it (so when you delete list[1], list[2] becomes list[1], hence the skip.

Here's a really easy way around it: (count down instead of up)


for(int i = list.size() - 1; i>=0; i--)
{
  if(condition...)
   list.remove(i);
}


You shouldn't remove items from a List while you iterate over it. Instead, use Iterator.remove() like:

for (Iterator<Object> it = list.iterator(); it.hasNext();) {
    if ( condition is true ) {
        it.remove();
    }
}