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

Java中如何根据指定RuleID过滤List排除对应RuleDesc

问题描述

需要实现过滤逻辑:当RuleType对象的ruleID属于指定排除集合(ruleIdsToExclude = "Type1,Type2,Type3,Type4")时,排除该对象的RuleDesc。现有测试数据如下:

rulesList              ArrayList
  [0]                  RuleType
     ruleDescr         “test1”
     ruleID            “Rule1”
  [1]                  Ruletype
     ruleDescr         “test2”
     ruleID            “Type2”
  [2]                  RuleType
     ruleDescr        "test3"
     ruleID           "Type3"
  [3]                  RuleType
     ruleDescr        "test4"
     ruleID           "Rule4"

过滤后最终列表应仅保留test1和test4,以下是修改后的Java代码实现:

修改后的代码
private List<String> extractAlertsInfoList(RulesListType thisDetailRulesList) {
    List<String> alertsInfoList = new ArrayList<>();
    if (thisDetailRulesList != null && CollectionUtils.isNotEmpty(thisDetailRulesList.getRule())) {
        List<RuleType> rulesList = thisDetailRulesList.getRule();
        // 初始化排除ID集合,转为HashSet提升查询效率
        Set<String> excludedRuleIds = new HashSet<>(Arrays.asList("Type1,Type2,Type3,Type4".split(",")));

        for (RuleType thisRule : rulesList) {
            String ruleId = thisRule.getRuleID().toString().trim();
            String ruleDesc = thisRule.getRuleDesc();
            // 仅保留描述有效且ID不在排除列表中的项
            if (isValidRuleDescription(ruleDesc) && !excludedRuleIds.contains(ruleId)) {
                alertsInfoList.add(ruleDesc);
            }
        }
    }
    return alertsInfoList;
}

private boolean isValidRuleDescription(String ruleDesc) {        
    return ruleDesc != null && !ruleDesc.isEmpty();
}
关键修改点
  • 将排除ID字符串转为HashSet:避免循环内重复分割字符串,同时HashSet的contains方法查询效率远高于List,优化性能
  • 新增排除判断:在原有描述有效性判断的基础上,增加!excludedRuleIds.contains(ruleId),确保不在排除集合中的规则才会被加入结果列表
  • 提前获取ruleDesc:减少重复调用getRuleDesc()的次数,提升代码简洁性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 12:57:52