0

I wanted to check if all the Strings from my ArrayList contain a letter "L".

If yes - than the string should have been removed.

I wonder why not every string with "L" was removed?

The result is:

Rose
Leier
Rose
Rose
Rose

Code:

list.add("Leier");
list.add("Rose");
list.add("Liebe");
list.add("Leier");
list.add("Leier");
list.add("Rose");
list.add("Leier");
list.add("Rose");
list.add("Leier");
list.add("Rose");
list.add("Leier");

for (int i = 0; i < list.size(); i++) {
    if (list.get(i).matches(".*[L].*")) {
            list.remove(i);
    }
}
Alex K.
  • 171,639
  • 30
  • 264
  • 288
alvira
  • 147
  • 1
  • 7

2 Answers2

1

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")

Joni
  • 108,737
  • 14
  • 143
  • 193
-1

Try this, don't forget to make it lower case

for (int i = 0; i < list.size(); i++) {
            if (list.get(i).toString().toLowerCase().contains("l")) {

                list.remove(i);
            }
        }
Marios
  • 26,333
  • 8
  • 32
  • 52
Badr Alwattar
  • 42
  • 1
  • 4