Java for循环中使用removeIf过滤Tariff时循环提前退出如何修复
问题根因
- 你用普通索引for循环遍历
plan2列表的同时,直接调用removeIf删除列表内的Plan元素,列表动态缩容后索引错位,就会出现跳过元素、循环提前终止的问题。 - 内层遍历Tariff的循环完全冗余,
removeIf本身就会一次性遍历列表删除所有符合条件的元素,不需要额外套一层for循环重复执行删除逻辑。
修复方案
直接用增强for循环先处理所有Plan的tariff过滤,最后统一移除空tariff的Plan即可,代码简化后如下:
List<Plan> plan2 = new ArrayList<>(tplan2); // 逐个处理每个Plan的关联tariff列表 for (Plan plan : plan2) { // 一次性删除所有type不等于"L"的tariff plan.getTariff().removeIf(tarifs -> !"L".equals(tarifs.getType())); } // 统一移除所有tariff为空的Plan plan2.removeIf(plan -> plan.getTariff().isEmpty());
如果你的业务场景需要在处理完单个Plan的tariff后就立刻移除空列表的Plan,可以用迭代器遍历避免索引异常:
List<Plan> plan2 = new ArrayList<>(tplan2); Iterator<Plan> planIterator = plan2.iterator(); while (planIterator.hasNext()) { Plan plan = planIterator.next(); plan.getTariff().removeIf(tarifs -> !"L".equals(tarifs.getType())); if (plan.getTariff().isEmpty()) { planIterator.remove(); } }
内容的提问来源于stack exchange,提问作者Deividas.r
相关产品推荐
相关产品推荐

