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

从ArrayList的字符串中按用户邮箱存储数据应选用什么数据结构?

数据结构选型方案

核心选型

推荐使用 HashMap<String, List<自定义实体类>> 作为存储结构,完全匹配你的业务需求:

  • 外层HashMap以邮箱作为key,满足按邮箱维度聚合查询的需求,单条查询复杂度为O(1)
  • 内层List存储同一邮箱对应的多条业务记录,适配同个邮箱可能对应多组数据的场景(比如你的示例中john@email.com就有2条不同的记录)

具体实现示例(Java)

1. 先定义业务实体类(推荐)

封装拆分后的前两段内容,避免无类型的字符串拼接或者数组带来的维护问题,Java 16+可以直接用record简化代码:

// JDK 16+ 写法
record RequestRecord(String id, String status) {}

// 低版本JDK写法
class RequestRecord {
    private final String id;
    private final String status;

    public RequestRecord(String id, String status) {
        this.id = id;
        this.status = status;
    }

    // 按需添加getter、toString方法
}

2. 初始化存储结构&写入数据

// 初始化存储容器
Map<String, List<RequestRecord>> emailRecordMap = new HashMap<>();

// 遍历你的原始ArrayList
for (String rawStr : yourArrayList) {
    String[] splitResult = rawStr.split(",");
    // 非法格式校验,避免数组越界
    if (splitResult.length != 3) {
        continue;
    }
    String id = splitResult[0];
    String status = splitResult[1];
    String email = splitResult[2];
    // 邮箱首次出现时自动初始化对应的List
    emailRecordMap.computeIfAbsent(email, k -> new ArrayList<>())
                  .add(new RequestRecord(id, status));
}

简化实现(不需要单独定义类的场景)

如果不想额外定义实体类,可以用JDK自带的AbstractMap.SimpleEntry存储两个字段:

// 存储结构定义
Map<String, List<Map.Entry<String, String>>> emailRecordMap = new HashMap<>();

// 写入逻辑
emailRecordMap.computeIfAbsent(email, k -> new ArrayList<>())
              .add(new AbstractMap.SimpleEntry<>(id, status));

注意:如果你的业务可以确定每个邮箱只会对应一条记录,内层可以去掉List,直接存储单个RequestRecord或者SimpleEntry即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:39:04