一:我們有這麼一列資料:
資料格式
m1的資料格式如下: margeKey 是 要按照 那個key來進行分組,key 名字
[{active_user=2, company_id=13}, {active_user=1, company_id=126}, {company_id=13, material_num=13}, {company_id=126, material_num=2}, {company_id=13, learning_duration=4315.0}, {company_id=126, learning_duration=5.0}, {company_id=13, daily_answer_times=2}, {company_id=126, daily_answer_times=2}, {company_id=126, exam_times=1}]
使用如下代碼,組裝成:
代碼如下:
public static List<Map<String, Object>> merge(List<TreeMap<String, Object>> m1,String mergeKey){
Set<String> set = new HashSet<>();
System.out.println("m1的資料格式是:"+m1);
return m1.stream()
.filter(map->map.get(mergeKey)!=null)
.collect(Collectors.groupingBy(o->{
//暫存所有key
set.addAll(o.keySet());
//按mergeKey分組
return o.get(mergeKey).toString();
}))
.entrySet().stream().map(o->{
//合并
Map<String, Object> map = o.getValue().stream().flatMap(m->{
return m.entrySet().stream();
}).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a,b)->b));
//為沒有的key指派0
set.stream().forEach(k->{
if(!map.containsKey(k)) map.put(k, 0);
});
return map;
}).collect(Collectors.toList());
}
// 一些個人碰坑總結:
// 通過分組的時候,一定的注意 分組的key 的value 的資料類型,資料類型不一樣,分組出的結果不一樣。
組裝成的資料格式如下: