When you remove an item from a list, it shifts all the remaining items towards the front of the list. So let's say you remove the item at index 5
: now the item at index 6 shifts to the position of 5, and 7 to 6, and so on.
After removing the item you increment i
, so next you examine index 6. But index 6 contains the item that used to be in index 7 - you've skipped over an item!
There are several ways to fix this. One is using the higher level removeIf
method.
list.removeIf(item -> item.matches(".*[L].*"));
Another is using an Iterator
to iterate over the list, and remove items.
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
String item = iterator.next();
if (item.matches(".*[L].*")) {
iterator.remove();
}
}
A third is reversing the order of iteration: if you iterate starting from the back of the list, changes to the list indices don't affect you.
for (int i = list.size() - 1; i >= 0; i--) {
if (list.get(i).matches(".*[L].*")) {
list.remove(i);
}
}
By the way, if you really only need to check if a string contains the letter L
, it's easier to use the contains
method instead of matches
: item.contains("L")