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

如何用Java Stream将List<Snippet>转为双层Map嵌套List的结构

解决方法

你现有代码的问题是第二层使用了Collectors.toMap,该收集器的value映射为单个对象,遇到同page的多个Snippet还会抛出重复键异常。要得到内层为List<Snippet>的结构,把第二层的toMap替换为Collectors.groupingBy即可,groupingBy默认会将同组元素收集为List:

List<Snippet> input = ....;
Map<Integer, Map<Integer, List<Snippet>>> result = input.stream()
        .collect(Collectors.groupingBy(
                Snippet::getDocId,
                Collectors.groupingBy(Snippet::getPage)
        ));

可选扩展

如果你需要内层List用指定的集合实现(比如要保持插入顺序用LinkedList),可以给第二层groupingBy指定下游收集器:

Map<Integer, Map<Integer, List<Snippet>>> result = input.stream()
        .collect(Collectors.groupingBy(
                Snippet::getDocId,
                Collectors.groupingBy(
                        Snippet::getPage,
                        Collectors.toCollection(LinkedList::new)
                )
        ));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 09:09:02