HashMap<String, List<CommodityEntity>> 现在有这么一个类型的数据,我要给它实现key和value都支持模糊搜索功能。请帮我写Java代码。返回的依然是 HashMap<String, List<CommodityEntity>>
时间: 2024-05-28 15:11:03 浏览: 117
好的,让我来实现这个功能。可以通过以下代码实现:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FuzzySearch {
/**
* 模糊搜索方法
*
* @param map 原始HashMap<String, List<CommodityEntity>>对象
* @param key 搜索的键值
* @param condition 模糊搜索条件
* @return 返回模糊搜索后的HashMap<String, List<CommodityEntity>>对象
*/
public static HashMap<String, List<CommodityEntity>> search(HashMap<String, List<CommodityEntity>> map, String key, String condition) {
HashMap<String, List<CommodityEntity>> result = new HashMap<String, List<CommodityEntity>>();
// 正则表达式匹配模糊搜索条件
String regex = ".*" + condition + ".*";
Pattern pattern = Pattern.compile(regex);
// 遍历原始HashMap进行模糊搜索
for (Entry<String, List<CommodityEntity>> entry : map.entrySet()) {
String str = entry.getKey();
Matcher matcher = pattern.matcher(str);
if (matcher.matches()) {
List<CommodityEntity> commodityList = entry.getValue();
result.put(str, commodityList);
}
}
return result;
}
public static void main(String[] args) {
// 初始化一个包含数据的HashMap对象
HashMap<String, List<CommodityEntity>> map = new HashMap<String, List<CommodityEntity>>();
List<CommodityEntity> list1 = new ArrayList<CommodityEntity>();
CommodityEntity commodity1 = new CommodityEntity("苹果手机");
CommodityEntity commodity2 = new CommodityEntity("苹果电脑");
list1.add(commodity1);
list1.add(commodity2);
map.put("苹果", list1);
List<CommodityEntity> list2 = new ArrayList<CommodityEntity>();
CommodityEntity commodity3 = new CommodityEntity("小米手机");
CommodityEntity commodity4 = new CommodityEntity("小米电视");
list2.add(commodity3);
list2.add(commodity4);
map.put("小米", list2);
// 调用模糊搜索方法
HashMap<String, List<CommodityEntity>> result = FuzzySearch.search(map, "苹", "手机");
// 输出结果
for (Entry<String, List<CommodityEntity>> entry : result.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
class CommodityEntity {
private String name;
public CommodityEntity(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "CommodityEntity [name=" + name + "]";
}
}
需要注意的是,使用正则表达式进行模糊搜索时,匹配的条件是“.*条件.*”,即前后可以是任意字符,中间必须包含条件字符。
阅读全文