如何用Java 8 Lambda按Id分组列表对象,整合QuestionDTO到对应QuestionEventDTO
基于Java 8 Lambda的合并分组实现方案
核心逻辑为「按id分组→同组收集QuestionDTO→构造合并结果」,实现代码简洁高效,仅需两次Stream流式处理即可完成:
import java.util.List; import java.util.stream.Collectors; // 原始查询结果列表 List<QuestionEventDTO> originalList = // 数据库查询返回的结果 List<QuestionEventDTO> mergedList = originalList.stream() // 第一步:按QuestionEventDTO的id分组 .collect(Collectors.groupingBy(QuestionEventDTO::getId)) .entrySet() .stream() // 第二步:对每个id分组做合并处理 .map(entry -> { // 收集当前分组下所有的QuestionDTO List<QuestionDTO> questions = entry.getValue() .stream() .map(QuestionEventDTO::getQuestion) .collect(Collectors.toList()); // 构造合并后的QuestionEventDTO对象 QuestionEventDTO mergedEvent = new QuestionEventDTO(); mergedEvent.setId(entry.getKey()); mergedEvent.setQuestion(null); mergedEvent.setQuestions(questions); return mergedEvent; }) .collect(Collectors.toList());
优化说明
- 若不需要保留原始列表的对象数据,可复用分组内的第一个对象实例,减少对象创建开销:
.map(entry -> { List<QuestionDTO> questions = entry.getValue() .stream() .map(QuestionEventDTO::getQuestion) .collect(Collectors.toList()); // 复用分组内第一个实例,无需新建对象 QuestionEventDTO mergedEvent = entry.getValue().get(0); mergedEvent.setQuestion(null); mergedEvent.setQuestions(questions); return mergedEvent; })
- 你提供的示例中出现的
questao为拼写误差,实际处理时以实体类定义的question字段为准即可。 - 若业务要求QuestionDTO做深拷贝,只需在
map(QuestionEventDTO::getQuestion)步骤补充对应的拷贝逻辑即可。
内容的提问来源于stack exchange,提问作者Romeu Fernandes Bessa
相关产品推荐
相关产品推荐

