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

如何优化Java列表过滤逻辑?避免重复调用工具方法

优化方案

当然可以优化,核心思路就是把ValidationUtil.getColorfulValues的调用结果缓存起来,每个color只计算一次,下面给两种常见的实现方式:

方式一:用map提前计算结果(更清晰的流式风格)

先通过map将每个color和对应的colorfulValues绑定成键值对,过滤时直接用提前计算好的值,最后再提取出符合条件的color:

private List<String> validate(StartValue start, List<String> colors, Entity entity) {
    if (CollectionUtils.isEmpty(colors)) {
        return colors;
    }
    String targetColor = entity.getColor(); // 提前提取,避免每次过滤重复调用
    return colors.stream()
                 .map(color -> new AbstractMap.SimpleEntry<>(color, ValidationUtil.getColorfulValues(start, color.getRGBValue())))
                 .filter(entry -> {
                     Collection<?> colorfulValues = entry.getValue();
                     return colorfulValues.isEmpty() || colorfulValues.contains(targetColor);
                 })
                 .map(AbstractMap.SimpleEntry::getKey)
                 .collect(Collectors.toList());
}

方式二:在filter的Lambda块中缓存结果(更紧凑)

如果不想引入键值对,可以直接在filter的Lambda代码块里先计算一次结果,再用这个结果做判断:

private List<String> validate(StartValue start, List<String> colors, Entity entity) {
    if (CollectionUtils.isEmpty(colors)) {
        return colors;
    }
    String targetColor = entity.getColor();
    return colors.stream()
                 .filter(color -> {
                     Collection<?> colorfulValues = ValidationUtil.getColorfulValues(start, color.getRGBValue());
                     return colorfulValues.isEmpty() || colorfulValues.contains(targetColor);
                 })
                 .collect(Collectors.toList());
}

额外优化说明

  • 提前提取entity.getColor()的值,避免在每次过滤迭代中重复调用(如果getColor()涉及复杂逻辑或返回值可能变化,这个优化会更有价值)
  • 两种方式都把原本三次的方法调用降到了一次,如果getColorfulValues是涉及复杂计算、数据库查询或IO操作的方法,性能提升会非常明显

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 14:15:13