1

In first list I have 3 Plans. In second list I have 3 Tarifs. I should to check every tariff and remove it from Plans if type not equals "L". In my case I have 2 tarifs which I need to remove. But problem is that when the first plan are been deleted, system won't go to other tariff and exiting the for loop. How to fix it?

List<Plan> plan2 = new ArrayList<Plan>();
    plan2.addAll(tplan2);
    
    for (int i = 0; i < plan2.size(); i++) { 
        List<Tarifs> tariff = new ArrayList<Tarifs>();
        tariff.addAll(plan2.get(i).gettariff());

        for (int j = 0; j < tariff.size(); j++) { 
            Tarifs tarifas = tariff.get(j); 
            Predicate<Tarifs> condition = Tarifs -> !Tarifs.getType().equals("L");
            plan2.get(i).getTariff().removeIf(condition);
        } 
        if(plan2.get(i).gettariff().isEmpty()) {
            plan2.removeIf(condition -> condition.getTariff().isEmpty());
        }
Deividas.r
  • 17
  • 1
  • maybe "continue" helps? – nurmanbetov Sep 14 '21 at 09:06
  • 1
    You are altering lists while iterating them. Dodgy. Use a copy of the list, or use `Iterator.remove()` – Stewart Sep 14 '21 at 09:06
  • Looks like one of those 'can't iterate through an object and remove things from it at the same time' issues. Try creating a copy of Plans and iterate through that, but do the removal from the original? – mcalex Sep 14 '21 at 09:07
  • do you use the list `tariff` anywhere else in your code or only to remove element? You could do that using only `plan2.get(i).getTariff()`and the stream api. Unrelated: try to follow [java code convention](https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html) (variable `tarifs` instead of `Tarifs`) – jhamon Sep 14 '21 at 09:09
  • The inner loop seems redundant, since you don't use the value of `tarifas`. – Andy Turner Sep 14 '21 at 09:10

2 Answers2

2

removeIf already does the looping for you.

Let's say you have a list of plans e.g (a, b, c),
and each plan has a list of tariff e.g (a has 1, 2, 3)

What you need to do is the following:

plans.forEach(plan -> {
    plan.getTariff().removeIf(condition);
});
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Mohhamed Nabil
  • 4,104
  • 1
  • 15
  • 11
1

I think the easiest way would be to move the removeIf outside the loop:

for (int i = 0; i < plan2.size(); i++) { 
  // Maybe remove things from tarrifs...
}

plan2.removeIf(condition -> condition.getTariff().isEmpty());
Andy Turner
  • 137,514
  • 11
  • 162
  • 243