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

如何用Java Stream按parent_id分组构建Map<Long, List<Child>>

问题:根据parent_id分组List为Map<Long, List>

我有一个List<Child>集合,想要遍历它并按照parent_id的唯一值分组,构建成Map<Long, List<Child>>。

示例数据

父表

project_idproject_desc
1One
2Two

子表

child_idparent_idcode
11code1
21code2
31code3
42code4
42code5

错误尝试代码

我尝试了以下代码,但运行时抛出异常:

List<Child> childEntityList = // 初始化列表

Map<Long, List<Child>> childEntityMap = childEntityList.stream()
    .collect(Collectors.toMap(
        childEntity -> childEntity.getParent().getParentId(), 
        childEntity -> childEntity
    ));

问题原因

Collectors.toMap()默认不处理重复key的情况,当多个Child对象对应同一个parent_id时,会抛出IllegalStateException——它不知道如何合并重复key对应的多个值。

正确解决方案

分组场景应该用Collectors.groupingBy(),它会自动将相同key的元素收集到List中,完全适配需求:

方案1:通过父对象获取parent_id

import java.util.stream.Collectors;

// 初始化列表
List<Child> childEntityList = ...;

Map<Long, List<Child>> childEntityMap = childEntityList.stream()
    .collect(Collectors.groupingBy(child -> child.getParent().getParentId()));

方案2:如果Child类有直接获取parent_id的方法

如果Child类本身提供了getParentId()方法(无需通过父对象调用),代码可以更简洁:

Map<Long, List<Child>> childEntityMap = childEntityList.stream()
    .collect(Collectors.groupingBy(Child::getParentId));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:20:33