0

For example, I have a list of strings say:

List<String> strs = new ArrayList<String>();
strs.add("A");
strs.add("B");
strs.add("C");
strs.add("D");

I want to loop over the list and get some elements, but at the same time, I want to remove some elements. Let's say:

for (int i = 0; i < strs.size(); i++) {
    String element = strs.get(i);
    System.out.println(element);
    strs.remove("A")
}

In the above example, element would be "A", "C", "D". But what I want is "A", "B", "C", "D". The above code is just an example, there could be other elements I want to remove, such as:

for (int i = 0; i < strs.size(); i++) {
    String element = strs.get(i);
    System.out.println(element);
    if (condition A) { strs.remove("A"); }
    if (condition B) { strs.remove("B"); }
    if (condition D) { strs.remove("D"); }
}

In this case, the size of the List strs would change depends on different conditions. And sometimes element jump from "A" to "C" without "B". What I have tried so far is created a list of indexes in my notebook. I know that remove element "A" will make the for loop ignore "B", but when this comes to other cases, the indexes don't work anymore. Is there a final algorithm or solution that can check every element inside the for loop?

Notice: Without using Iterator, List.removeAll, or i-- (Since I sometimes get Time Limit Exceed when use i--).

Marc Le Bihan
  • 2,308
  • 2
  • 23
  • 41
William Ji
  • 23
  • 5
  • 1
    You'll want to use an iterator and `remove()`. Or just put `i--` after you've removed an element in your for loop. – Matthieu Oct 03 '20 at 07:10
  • @user7 I took a look at that answer, but is there a way without using iterator and remove all? – William Ji Oct 03 '20 at 07:11
  • 1
    Looks like a XY problem. It's more likely that the TLE is caused by your algorithm being wrong (or just not fast enough), not `i--`. Alternatively look for how to filter a list. – user202729 Oct 03 '20 at 07:31

0 Answers0