You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java如何判断List中同时存在两个编码并移除不符合条件的Tariff

问题解决方法

现有代码问题

  • 布尔标记t定义位置错误:你将它定义在所有Plan循环的外层,一旦某个Plan满足条件将t设为true,后续所有Plan的判断都会被这个值影响,逻辑完全错误,需要把它移到每个Plan的循环内部,每次遍历新Plan都重置为false
  • 校验逻辑冗余:三层循环完全没必要,判断是否同时存在编码为N和M的Tariff,只要分别做两次存在性校验即可,不需要嵌套遍历
  • 删除方法使用错误:removeAll()需要传入要删除的元素集合作为参数,你要清空所有Tariff直接调用集合的clear()方法即可,或者直接给Plan的tariff属性set一个空集合

修正后的基础版本代码

List<Plan> planList = new ArrayList<>(plans2);

for (Plan plan : planList) {
    List<Tariff> tariffList = plan.getTariff();
    boolean hasN = false;
    boolean hasM = false;
    // 遍历一次即可同时校验两个编码是否存在
    for (Tariff tariff : tariffList) {
        String code = tariff.getCode();
        if ("N".equals(code)) {
            hasN = true;
        } else if ("M".equals(code)) {
            hasM = true;
        }
        // 两个都找到可以提前跳出循环,优化性能
        if (hasN && hasM) {
            break;
        }
    }
    // 不同时存在就清空所有Tariff
    if (!(hasN && hasM)) {
        tariffList.clear();
        // 如果getTariff()返回的是不可变集合,就用set方法替换:
        // plan.setTariff(new ArrayList<>());
    }
}

简化版本(JDK8+ Stream实现)

如果你的项目使用JDK8及以上版本,可以用Stream进一步简化代码,逻辑更清晰:

List<Plan> planList = new ArrayList<>(plans2);
planList.forEach(plan -> {
    boolean hasBoth = plan.getTariff().stream()
            .map(Tariff::getCode)
            .filter(code -> "N".equals(code) || "M".equals(code))
            .distinct()
            .count() == 2;
    if (!hasBoth) {
        plan.getTariff().clear();
    }
});

注意:如果Plan.getTariff()返回的是不可变集合(比如MyBatis查询返回的集合或者Collections.unmodifiableList包装的集合),调用clear()会抛出UnsupportedOperationException,这种情况直接调用plan.setTariff(new ArrayList<>())替换成新的空集合即可。

内容的提问来源于stack exchange,提问作者TtT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 10:45:02