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

如何用Java 8 Stream按category分组Standard对象至Map集合

使用Java 8 Stream实现Standard对象按category分组

当然可以!Java 8引入的Stream API配合Collectors.groupingBy()收集器,能非常简洁高效地完成你要的分组需求。下面是具体实现步骤:

1. 补全Standard类的必要方法

首先要确保你的Standard类有category属性的getter方法(Stream需要通过它提取分组的key),另外重写toString()方便后续验证结果:

public class Standard {
    private String studentName;
    private String category;

    // 构造方法
    public Standard(String studentName, String category) {
        this.studentName = studentName;
        this.category = category;
    }

    // 获取category的getter,分组必须
    public String getCategory() {
        return category;
    }

    // 重写toString,方便打印查看对象内容
    @Override
    public String toString() {
        return "Standard{" +
                "studentName='" + studentName + '\'' +
                ", category='" + category + '\'' +
                '}';
    }
}

2. 核心分组代码

接下来用Stream结合Collectors.groupingBy()完成分组:

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

public class CategoryGroupingDemo {
    public static void main(String[] args) {
        // 初始化你的Standard对象列表
        List<Standard> standardList = List.of(
                new Standard("ABC", "1"),
                new Standard("DEF", "2"),
                new Standard("IJK", "1"),
                new Standard("LMN", "2")
        );

        // 关键:用Stream分组得到目标Map
        Map<String, List<Standard>> groupedByCategory = standardList.stream()
                .collect(Collectors.groupingBy(Standard::getCategory));

        // 打印结果验证
        groupedByCategory.forEach((category, students) -> {
            System.out.printf("Category %s: %s%n", category, students);
        });
    }
}

代码解释

  • standardList.stream():将列表转换为Stream流,开启流式操作
  • Collectors.groupingBy(Standard::getCategory):
    • 这个收集器的作用是:以每个Standard对象的category值作为Map的key
    • 自动将拥有相同key的Standard对象收集到List<Standard>中,作为对应key的value
    • 最终返回你需要的Map<String, List<Standard>>类型

运行结果

执行代码后会输出:

Category 1: [Standard{studentName='ABC', category='1'}, Standard{studentName='IJK', category='1'}]
Category 2: [Standard{studentName='DEF', category='2'}, Standard{studentName='LMN', category='2'}]

完全符合你预期的分组效果。

如果需要自定义收集的集合类型(比如指定用ArrayList而非默认集合),可以重载groupingBy方法:

Map<String, List<Standard>> groupedMap = standardList.stream()
        .collect(Collectors.groupingBy(Standard::getCategory, Collectors.toList()));

不过默认情况下groupingBy已经会返回List,这个可以按需选择。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 19:02:48