从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
相关产品推荐
相关产品推荐

