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

如何用Java 8按属性分组并统计每组元素数量?

Java 8按分类统计元素数量问题

问题背景

给定如下JSON格式的数据:

[
   {
      "category":"Fruits",
      "name":"Apple"
   },
   {
      "category":"Fruits",
      "name":"Manggo"
   },
   {
      "category":"Vegetables",
      "name":"Water Spinach"
   }
]

期望通过Java 8流操作实现按category分组并统计每组的元素数量(预期结果:Fruits = 2, Vegetables = 1),但使用以下代码后未得到预期结果:

Map<String, List<MyData>> myData
    = list.stream().collect(Collectors.groupingBy(d -> d.getCategory()));

解决方案

当前代码仅实现了按分类分组并保留每组的对象列表,若要统计每组数量,需要在groupingBy中搭配下游收集器完成计数:

方式一:使用Collectors.counting()(返回Long类型计数)

Map<String, Long> categoryCountMap = list.stream()
    .collect(Collectors.groupingBy(MyData::getCategory, Collectors.counting()));

方式二:使用Collectors.summingInt()(返回Integer类型计数)

如果需要整数类型的计数结果,可替换下游收集器:

Map<String, Integer> categoryCountMap = list.stream()
    .collect(Collectors.groupingBy(MyData::getCategory, Collectors.summingInt(e -> 1)));

代码说明

  • Collectors.groupingBy(MyData::getCategory):指定以category字段作为分组的键
  • 下游收集器(counting()或summingInt()):负责统计每个分组内的元素数量,最终得到的Map键为分类名称,值为对应分类的元素个数,完全匹配预期结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:50:23