最近项目上有个需求由于数据比较庞大,从数据库取数据的时候比较耗费时间,所以为了能提高程序的性能,在未引入缓存的基础下,想尽量减少与数据库之间的交互,所以把需要的数据都以视图的方式将数据,放进一个结果集中List<map<String,Object>>中去,然后根据根据需求进行数据的抽取。
自己写了一个方法,方法的大概意思就是将结果集中的数据按照某一字段名称对数据进行重新排列,代码如下:
/**
* 將從數據庫中取到的結果集按照某一分類進行洗牌
* @param dataResult
* @param classification
* @return
*/
public Map<Object, List<Map<String, Object>>> classificationResult(List<Map<String, Object>> dataResult, String classification) {
/**
* 定义以某一个分类为基础的数据结果集
*/
Map<Object, List<Map<String, Object>>> studentMapListMap = new HashMap<Object, List<Map<String,Object>>>();
/**
* 循环数据库中的信息
*/
for (Map<String, Object> studentMap : dataResult) {
/**
* 判断数据这个分类的是否已经存在
*/
if(!studentMapListMap.containsKey(studentMap.get(classification))) {
/**
* 不存在则将这个分类和与该条分类下的第一条数据存起来
*/
List<Map<String, Object>> tempListMap = new ArrayList<Map<String,Object>>();
tempListMap.add(studentMap);
studentMapListMap.put(studentMap.get(classification), tempListMap);
}else {
/**
* 如果这个分类已经存在,则将新的数据存储起来,分类名称用之前的
*/
studentMapListMap.get(studentMap.get(classification)).add(studentMap);
}
}
return studentMapListMap;
}在写这个需求的过程中在网上看到了另外一个方法,是去重的方式进行数据的筛选:
/**
* 根据map中的某个key 去除List中重复的map
* @author shijing
* @param list
* @param mapKey
* @return
*/
public static List<Map<String, Object>> removeRepeatMapByKey(List<Map<String, Object>> list, String mapKey){
//if (CollectionUtils.isNullOrEmpty(list)) return null;
//把list中的数据转换成msp,去掉同一id值多余数据,保留查找到第一个id值对应的数据
List<Map<String, Object>> listMap = new ArrayList<>();
Map<String, Map> msp = new HashMap<>();
for(int i = list.size()-1 ; i>=0; i--){
//[xh = xh0, xm = xm0, xx = xx0……]
Map map = list.get(i);
// xh0
String id = (String)map.get(mapKey);
//[ xm = xm0, xx = xx0……]
map.remove(mapKey);
//{xh0=[xm = xm0, xx = xx0……]}
msp.put(id, map);
}
//msp为{xh0=[xm = xm0, xx = xx0……], xh1=[xm = xm1, xx = xx1……], ……}
//把msp再转换成list,就会得到根据某一字段去掉重复的数据的List<Map>
Set<String> mspKey = msp.keySet();//{xh0, xh1, ……}
for(String key: mspKey){
Map newMap = msp.get(key);//{xm = xm0, xx = xx0……}
newMap.put(mapKey, key);
listMap.add(newMap);
}
return listMap;
}以上两个方法所用的核心原理是基本是一致的,都用到的是map中的put方法存key的时候不能重复。