Dart中高效搜索Map内多维列表中字符串的方法
针对你这个大数据量下的商品部分匹配搜索需求,直接遍历原Map<String, List<List<String>>>结构肯定是行不通的——每次搜索都要扫遍所有日期下的所有商品,数据量一大就会卡成狗。最有效的优化方式是提前构建倒排索引,把搜索维度从「日期→商品」转成「商品→价格」,这样搜索效率能直接拉满。
高效实现商品部分匹配搜索的方案
一、核心思路:构建倒排索引
倒排索引的本质是把原数据的正向映射(日期对应一批商品+价格),转换为反向映射(商品对应所有关联的价格/日期+价格)。这样搜索时无需遍历全量数据,直接通过索引定位目标商品。
1. 基础索引(仅保留商品+价格)
如果只需要返回匹配商品的价格列表,可以构建一个Map<String, List<String>>类型的索引:
// 假设你的原始数据结构是这样的 Map<String, List<List<String>>> originalData = new HashMap<>(); // 构建倒排索引:键是商品名,值是该商品对应的所有价格列表 Map<String, List<String>> itemPriceIndex = new HashMap<>(); // 遍历原始数据填充索引 for (Map.Entry<String, List<List<String>>> dateEntry : originalData.entrySet()) { List<List<String>> dailyItems = dateEntry.getValue(); for (List<String> itemPricePair : dailyItems) { String item = itemPricePair.get(0); String price = itemPricePair.get(1); // 商品不存在则创建新列表,存在则直接追加价格 itemPriceIndex.computeIfAbsent(item, k -> new ArrayList<>()).add(price); } }
2. 增强索引(保留日期+价格)
如果需要展示每个价格对应的日期,可以把索引升级为Map<String, List<Map<String, String>>>,让结果更直观:
Map<String, List<Map<String, String>>> itemDatePriceIndex = new HashMap<>(); for (Map.Entry<String, List<List<String>>> dateEntry : originalData.entrySet()) { String date = dateEntry.getKey(); List<List<String>> dailyItems = dateEntry.getValue(); for (List<String> itemPricePair : dailyItems) { String item = itemPricePair.get(0); String price = itemPricePair.get(1); Map<String, String> datePriceInfo = new HashMap<>(); datePriceInfo.put("date", date); datePriceInfo.put("price", price); itemDatePriceIndex.computeIfAbsent(item, k -> new ArrayList<>()).add(datePriceInfo); } }
二、实现高效搜索逻辑
基于建好的索引,我们可以快速实现不同类型的部分匹配搜索。
1. 基础包含匹配
适合用户输入任意关键词,匹配所有包含该关键词的商品(支持不区分大小写):
public Map<String, List<String>> searchByKeyword(String keyword) { Map<String, List<String>> result = new HashMap<>(); String lowerKeyword = keyword.toLowerCase(); // 统一转小写实现不区分大小写 for (Map.Entry<String, List<String>> entry : itemPriceIndex.entrySet()) { String item = entry.getKey(); if (item.toLowerCase().contains(lowerKeyword)) { result.put(item, entry.getValue()); } } return result; }
2. 超大数据量进阶优化
如果商品数量达到几十万甚至上百万,上述遍历索引的方式仍有性能瓶颈,可以针对性优化:
- 前缀匹配用Trie树:构建前缀树(Trie)存储所有商品名,搜索时只需遍历前缀对应的分支,时间复杂度仅为O(L)(L为关键词长度),适合"前缀模糊搜索"场景。
- 复杂模糊匹配用全文检索:引入Apache Lucene这类轻量全文检索库,支持分词、模糊匹配、正则匹配等高级搜索,性能远超手动遍历。
三、额外优化建议
- 去重处理:如果同一件商品有重复价格,可以用
Set<String>存储价格,避免重复展示。 - 索引同步更新:如果原始数据会动态新增/删除,要同步更新索引(比如新增日期数据时,把新的商品-价格对加入索引;删除数据时,从索引中移除对应条目)。
- 热门搜索缓存:对高频搜索的关键词,缓存其结果,进一步提升响应速度。
内容的提问来源于stack exchange,提问作者Melvin Abraham
相关产品推荐
相关产品推荐

