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

如何使用Java Streams按颜色统计连衣裙数量并返回Map

Java Streams 实现按颜色统计连衣裙数量

直接用Stream的collect终端操作搭配Collectors工具类的分组、聚合方法就能完成需求,最简写法如下,返回结果完全匹配要求的Map<String, Integer>结构:

import java.util.Map;
import java.util.stream.Collectors;

// 业务逻辑实现
Map<String, Integer> colorToCountMap = dresses.stream()
        .collect(Collectors.groupingBy(
                Dress::getColor,
                Collectors.summingInt(e -> 1)
        ));

逻辑说明

  • 先调用stream()把连衣裙列表转为流对象
  • 外层用Collectors.groupingBy指定分组维度:以Dress实例的color属性作为分组键,也就是最终Map的key
  • 下游聚合收集器用Collectors.summingInt(e -> 1):每遍历到一个同分组的元素就累加1,直接返回Integer类型的计数结果,不需要额外做类型转换

可选写法

如果习惯用counting()收集器做计数,注意它默认返回Long类型结果,必须通过collectingAndThen做类型转换才能适配要求的Integer值类型:

Map<String, Integer> colorToCountMap = dresses.stream()
        .collect(Collectors.groupingBy(
                Dress::getColor,
                Collectors.collectingAndThen(
                        Collectors.counting(),
                        Long::intValue
                )
        ));

空值处理

如果业务场景中存在color为null的连衣裙数据,且不需要统计这类无效条目,可以在流操作中提前加过滤逻辑:

Map<String, Integer> colorToCountMap = dresses.stream()
        .filter(dress -> dress.getColor() != null) // 过滤掉颜色为空的无效数据
        .collect(Collectors.groupingBy(
                Dress::getColor,
                Collectors.summingInt(e -> 1)
        ));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 12:51:24