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

如何用Java Stream按ID实现Account对象列表的去重

问题:使用Java Stream按ID去重Account列表并保留最早记录

问题背景

通过数据库JOIN操作得到了包含重复ID的ArrayList<Account>列表,当前列表结构:

List<Account> accountList= new ArrayList<>();
accountList.add(new Account("123","ram","2023-05-09T13:30:00.000+00:00"));
accountList.add(new Account("123", "ram","2023-05-09T14:30:00.000+00:00"));

期望得到每个ID对应唯一的Account对象,且保留startDate最早的记录:

accountList.add(new Account("123","ram","2023-05-09T13:30:00.000+00:00"));

Account类定义:

public class Account {
    String id;
    String name;
    Date startDate;

    // 需自行实现构造方法、getter/setter
    public Account(String id, String name, Date startDate) {
        this.id = id;
        this.name = name;
        this.startDate = startDate;
    }

    public String getId() { return id; }
    public Date getStartDate() { return startDate; }
}

解决方案

利用Java Stream的Collectors.toMap实现按ID去重,键冲突时保留startDate更早的记录,最后将Map的值转为List即可。

代码实现

List<Account> uniqueAccounts = accountList.stream()
    .collect(Collectors.toMap(
        Account::getId,
        account -> account,
        (existing, newAccount) -> existing.getStartDate().before(newAccount.getStartDate()) 
            ? existing 
            : newAccount
    ))
    .values()
    .stream()
    .collect(Collectors.toList());

说明

  • 必须确保Account类提供getId()和getStartDate()的getter方法,否则Stream无法获取字段进行比较逻辑;
  • 示例中同一ID的name字段一致,若业务场景中存在同一ID对应不同name的情况,需根据实际需求调整冲突时的处理逻辑。

内容的提问来源于stack exchange,提问作者Developer and Thinker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:52:39