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

如何使用Java Streams将List转换为包含List的对象的Map?

将List转换为Map<String, AB>的实现方案

首先需要确保你的实体类具备必要的构造方法和Getter方法(原始类定义中缺少这些,实际使用时需要补充),修正后的类定义如下:

class A {
    String code;

    public String getCode() {
        return code;
    }

    public A(String code) {
        this.code = code;
    }
}

class B {
    A a;
    String value;

    public A getA() {
        return a;
    }

    public B(A a, String value) {
        this.a = a;
        this.value = value;
    }
}

class AB {
    A a;
    List<B> bList;

    public AB(A a, List<B> bList) {
        this.a = a;
        this.bList = bList;
    }

    public List<B> getBList() {
        return bList;
    }
}

方法一:使用groupingBy + collectingAndThen

这种方式先按A的code分组,再将每组的List<B>封装为AB对象:

List<B> sourceList = // 你的源数据列表
Map<String, AB> targetMap = sourceList.stream()
    .collect(Collectors.groupingBy(
        // 分组Key:取B中A的code
        b -> b.getA().getCode(),
        // 下游收集器:先把同组B收集为List,再转为AB对象
        Collectors.collectingAndThen(
            Collectors.toList(),
            bList -> {
                // 从同组的第一个B中获取A对象(同组B的A code一致)
                A a = bList.get(0).getA();
                return new AB(a, bList);
            }
        )
    ));

方法二:使用toMap处理重复Key

这种方式直接通过toMap构建结果,同时处理同一个code对应多个B的合并逻辑:

List<B> sourceList = // 你的源数据列表
Map<String, AB> targetMap = sourceList.stream()
    .collect(Collectors.toMap(
        // 生成Key:B中A的code
        b -> b.getA().getCode(),
        // 生成初始Value:将单个B封装为AB
        b -> new AB(b.getA(), new ArrayList<>(Collections.singletonList(b))),
        // 合并逻辑:当Key重复时,把新B添加到已有AB的列表中
        (existingAb, newAb) -> {
            existingAb.getBList().addAll(newAb.getBList());
            return existingAb;
        }
    ));

注意事项

  • 如果同组B对应的A对象不是同一个实例但code相同,业务上若需要统一AB中的A实例,可以提前对A按code做缓存复用,避免多个code相同但实例不同的A存在。
  • 两种方法都需要保证sourceList中不会出现B的a为null的情况,否则会抛出空指针异常,实际使用时可根据需求添加判空逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:04:56