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

如何用Java Stream将SimpleObject按TypeEnum聚合为ComplexObject

Java 8 Stream实现按TypeEnum聚合SimpleObject到ComplexObject

刚好做过类似的需求,用Java Stream的Collectors.groupingBy就能轻松搞定,给你完整的实现代码和拆解说明:

完整实现代码

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DataService {
    private final DataRepository dataRepo;

    public List<ComplexObject> getPackedData() {
        return dataRepo.getSimpleObjects().stream()
                // 1. 按TypeEnum分组,得到键为类型、值为对应SimpleObject列表的Map
                .collect(Collectors.groupingBy(SimpleObject::getType))
                // 2. 将Map的键值对转换为ComplexObject实例
                .entrySet().stream()
                .map(entry -> {
                    ComplexObject complexObj = new ComplexObject();
                    complexObj.setType(entry.getKey());
                    complexObj.setSimpleObjects(entry.getValue());
                    return complexObj;
                })
                // 3. 收集为ComplexObject列表返回
                .collect(Collectors.toList());
    }
}

关键步骤拆解

  • 分组操作:Collectors.groupingBy(SimpleObject::getType)是核心,它会自动把所有SimpleObject按照type属性归类,生成一个Map<TypeEnum, List<SimpleObject>>,这一步就完成了同一类型数据的聚合。
  • 转换为ComplexObject:遍历分组后的Map条目(entrySet()),用map操作把每个键值对转换成ComplexObject——键就是type属性,值就是对应的simpleObjects列表。
  • 收集结果:最后用Collectors.toList()把所有ComplexObject收集成List返回,如果你需要其他集合类型(比如Set),替换成对应的收集器即可。

简化优化(如果有构造器的话)

如果你的ComplexObject提供了带参数的构造器:

public class ComplexObject {
    private TypeEnum type;
    private List<SimpleObject> simpleObjects;

    public ComplexObject(TypeEnum type, List<SimpleObject> simpleObjects) {
        this.type = type;
        this.simpleObjects = simpleObjects;
    }
    // getter/setter 可选
}

那map操作可以简化成一行,代码更简洁:

.map(entry -> new ComplexObject(entry.getKey(), entry.getValue()))

注意事项

确保SimpleObject有getType()方法(用来获取分组依据的type属性),ComplexObject有对应的setter方法或者构造器来赋值属性,这是Stream操作能正常运行的前提。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:22:40