You need to enable JavaScript to run this app. 如何使用Java实现列表对象按ID去重并合并文本字段
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java实现列表对象按ID去重并合并文本字段

Java实现列表对象分组去重合并的可行方案

该实现完全对齐SQL中 GROUP BY id + GROUP_CONCAT(text) 的逻辑,可直接实现题目给出的输入输出转换效果。

前置实体定义

定义和示例字段匹配的输入、输出结构:

// 输入单条记录结构
class InputRecord {
    private Integer id;
    private String text;
    // 构造方法、getter、setter 省略
}

// 输出聚合记录结构
class OutputRecord {
    private Integer id;
    private List<String> text;
    // 构造方法、getter、setter 省略
}

具体实现

Java 8+ 版本(Stream流实现,最常用)

利用Stream内置的分组收集能力,两步完成聚合:

  • 遍历输入列表,按id字段做分组键
  • 收集同组下所有text字段为列表,最终映射为目标输出对象
// 对应题目给出的输入列表
List<InputRecord> inputList = Arrays.asList(
    new InputRecord(1, "123"),
    new InputRecord(1, "456"),
    new InputRecord(1, "789"),
    new InputRecord(2, "111")
);

// 执行分组聚合
List<OutputRecord> outputList = inputList.stream()
    .collect(Collectors.groupingBy(
        InputRecord::getId,
        Collectors.mapping(InputRecord::getText, Collectors.toList())
    ))
    .entrySet()
    .stream()
    .map(entry -> new OutputRecord(entry.getKey(), entry.getValue()))
    .toList();

执行结果和题目给出的示例输出完全一致。

低版本Java兼容实现

Java 8之前无StreamAPI支持时,可通过临时Map手动维护分组关系,逻辑和Stream版本完全一致:

// 初始化分组临时Map
Map<Integer, List<String>> groupMap = new HashMap<>();
// 遍历输入完成分组
for (InputRecord record : inputList) {
    Integer id = record.getId();
    String text = record.getText();
    groupMap.putIfAbsent(id, new ArrayList<>());
    groupMap.get(id).add(text);
}
// 生成最终输出列表
List<OutputRecord> outputList = new ArrayList<>();
for (Map.Entry<Integer, List<String>> entry : groupMap.entrySet()) {
    outputList.add(new OutputRecord(entry.getKey(), entry.getValue()));
}

扩展调整说明

  • 需要对同组text值去重时,将收集逻辑替换为去重实现即可:不需要保序直接用Collectors.toSet()收集;需要保留元素出现顺序的去重,用LinkedHashSet收集后转List,完全对齐SQL中GROUP_CONCAT(DISTINCT text)的效果。
  • 需要维持text的原始出现顺序时,使用默认的ArrayList、Collectors.toList()即可,不会打乱元素的原始顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 08:45:04