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

如何使用Java 8函数式API将Map<String, List<List<String>>>转换为Map<String, List<String>>

解决Java 8分组后扁平化嵌套列表的问题

你的代码返回Map<String, List<List<String>>>的原因是:mapping收集器将每个类实例转换为一个包含目标value的流(或列表),再通过Collectors.toList()收集这些流/列表,最终形成了嵌套结构。要得到单层的List<String>,可以用以下两种Java 8兼容的实现方式:

方法一:先关联ID与Value,再分组

先通过flatMap将每个类实例下符合条件的value与对应id绑定,再进行分组收集:

class.stream()
    .flatMap(item -> item.sub().stream()
                         .filter(subItem -> subItem.type().equals(1))
                         .map(subItem -> new AbstractMap.SimpleEntry<>(item.id(), subItem.value())))
    .collect(Collectors.groupingBy(
        Map.Entry::getKey,
        Collectors.mapping(Map.Entry::getValue, Collectors.toList())
    ));

这种方式通过SimpleEntry保留了id和value的关联关系,flatMap直接展开所有符合条件的value,最后分组时直接收集为单层列表。

方法二:在分组下游收集器中扁平化嵌套结构

基于你原有的分组逻辑,通过Collectors.collectingAndThen对嵌套的列表进行后处理扁平化:

class.stream().collect(Collectors.groupingBy(class::id,
    Collectors.collectingAndThen(
        Collectors.mapping(item -> 
            item.sub().stream()
              .filter(subItem -> subItem.type().equals(1))
              .map(subItem::value)
              .collect(Collectors.toList()),
        Collectors.toList()),
        nestedList -> nestedList.stream().flatMap(List::stream).collect(Collectors.toList())
    )
));

这里collectingAndThen先按原有逻辑收集到List<List<String>>,再通过flatMap将嵌套列表展开为单层列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:47:47