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

如何用Java Stream API将对象列表字段收集为Map<String,ArrayList<String>>

实现代码

你可以通过flatMap打平嵌套集合再分组的方式实现,和原for循环逻辑完全一致:

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

// 核心逻辑
Map<String, ArrayList<String>> result = assistantList.stream()
    .flatMap(assistant -> assistant.getSupervisorList().stream()
        .map(supervisor -> new AbstractMap.SimpleEntry<>(assistant.getLogin(), supervisor.getLogin())))
    .collect(Collectors.groupingBy(
        Map.Entry::getKey,
        Collectors.mapping(
            Map.Entry::getValue,
            Collectors.toCollection(ArrayList::new)
        )
    ));

逻辑说明

  • 用flatMap将双层循环打平,生成所有「助理登录名-主管登录名」的键值对,和原代码的双层for循环遍历逻辑完全对应
  • Collectors.groupingBy的作用和原代码中map.computeIfAbsent逻辑一致:不存在对应键时自动初始化集合,存在时直接向集合追加元素
  • 末尾指定Collectors.toCollection(ArrayList::new)是为了严格对齐原代码中值类型为ArrayList的要求,如果不需要严格限定List的实现类,也可以替换为Collectors.toList()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 17:18:05