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

Java 1.8下统计List A中存在于List B的元素数量的高效实现方法

Java 8 高效统计两个ArrayList共同元素数量方案

核心思路

将查找复杂度较高的List转为HashSet(contains操作时间复杂度为O(1)),搭配Java 8 Stream API实现简洁高效的统计,总时间复杂度为O(m+n)(m为listA长度,n为listB长度),远优于传统双层遍历的O(m*n)。

实现代码

基础写法(适用于listB数据量较小的场景)

List<String> listA = new ArrayList<>();
List<String> listB = new ArrayList<>();

// 统计共同元素数量,listA中重复元素会按实际出现次数计数
long commonCount = listA.stream()
        .filter(new HashSet<>(listB)::contains)
        .count();

优化写法(适用于listB数据量较大的场景,避免重复创建Set实例)

// 提前将listB转为HashSet复用
HashSet<String> setB = new HashSet<>(listB);
long commonCount = listA.stream()
        .filter(setB::contains)
        .count();

变种:统计listA去重后的共同元素数量

HashSet<String> setB = new HashSet<>(listB);
long distinctCommonCount = listA.stream()
        .distinct()
        .filter(setB::contains)
        .count();

注意事项

  • 若需要自定义匹配规则(如字符串忽略大小写匹配),可自行修改filter内的判断逻辑即可。
  • 如果集合存储的是自定义类而非String,需要确保类已经正确重写equals()和hashCode()方法,否则HashSet的匹配逻辑会失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 15:18:00