在Java中如何按条件统计List数量_Java集合计数方法

Java中按条件统计List数量推荐用Stream.filter().count(),也可用Collectors.counting()、传统for循环或Apache Commons Collections的countMatches(),需据Java版本和需求选择。

在Java中按条件统计List数量,核心是遍历集合并判断每个元素是否满足条件,再累加计数。Java 8+ 推荐用Stream API简洁实现,老版本可用传统for循环或增强for循环。

用Stream.filter().count()(推荐,Java 8+)

这是最常用、可读性高且函数式风格的方法。先用filter()筛选符合条件的元素,再用count()获取数量。

  • 适用于任意对象List,条件写在Lambda表达式里
  • 不会修改原List,线程安全(前提是数据源不变)
  • 示例

    :统计字符串List中长度大于3的元素个数
List list = Arrays.asList("a", "hello", "hi", "world");
long count = list.stream().filter(s -> s.length() > 3).count(); // 结果为2

用Collectors.counting()配合collect()

适合需要同时做其他聚合操作(如分组+计数)的场景,单独计数略显冗余,但语义更明确。

  • 与filter联用,本质和count()类似,但属于归约操作
  • 示例:统计年龄大于18的用户数
List users = ...;
long adultCount = users.stream()
  .filter(u -> u.getAge() > 18)
  .collect(Collectors.counting());

传统for循环(兼容所有Java版本)

在性能敏感或需兼容Java 7及以下时仍实用,逻辑清晰,无额外对象开销。

  • 手动维护计数器变量,适合简单条件或调试时逐步检查
  • 注意避免空指针:遍历前判空,或在lambda/条件中处理null
int count = 0;
for (String s : list) {
  if (s != null && s.length() > 3) {
    count++;
  }
}

用Apache Commons Collections(第三方库)

若项目已引入commons-collections4,可用CollectionUtils.countMatches(),语义直接。

  • 依赖Predicate接口,写法类似Stream filter
  • 需添加Maven依赖:org.apache.commons:commons-collections4
int count = CollectionUtils.countMatches(list,
  str -> str != null && str.length() > 3);

基本上就这些。Stream方式最主流,for循环最稳妥,第三方工具类适合已有依赖的项目。关键是根据Java版本、可读性要求和性能需求选合适的方式。