Home > Software engineering >  Java removeIf condition in for loop
Java removeIf condition in for loop

Time:09-17

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());
        }

CodePudding user response:

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);
});

CodePudding user response:

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());
  • Related