n个List合并,Map中某属性值相等的value值相加

时间:2023-03-09 09:18:20
n个List<Map>合并,Map中某属性值相等的value值相加
List<Map> maps1 =[{"bigtypes":100,"num":400},{"bigtypes":200,"num":300},{"bigtypes":400,"num":500},{"bigtypes":600,"num":500}]

List<Map> maps2 =[{"bigtypes":400,"num":720},{"bigtypes":500,"num":320},{"bigtypes":200,"num":120}]

List<Map> maps3 =[{"bigtypes":700,"num":120},{"bigtypes":500,"num":320},{"bigtypes":100,"num":510}]

目的为将  bigtypes 属性值相等 num属性值进行相加,bigtypes属性值不相等的List<Map>累加

将json数组循环赋值给  foodIntakeType

            List<TDiet> tDiets = dietApiService.getDietsByDate(userId, startDate, endDate);
List<Map<String, String>> list = new ArrayList();
List<Map<String, String>> newList = new ArrayList();
int talls=0;
if(tDiets.size()>0){
int a=0;
for(TDiet td:tDiets){
talls+=Integer.parseInt(td.getFoodIntakeMeasure());//摄入总量
a++;
String foodIntakeType =td.getFoodIntakeType();
org.json.JSONArray jsonArray = new org.json.JSONArray(foodIntakeType);
int iSize = jsonArray.length();
for (int i = 0; i < iSize; i++) {
org.json.JSONObject jsonObj = jsonArray.getJSONObject(i);
String bigtypes = jsonObj.get("bigtypes").toString();
String num = jsonObj.get("num").toString();
Map<String, String> maMap = new HashMap<String, String>();
maMap.put("bigtypes", bigtypes);
maMap.put("num", num);
if(a>1){//多组数据
newList=list;
Map<String,String> newMap =new HashMap<String, String>();
int b=0;
for (int j = 0; j < list.size(); j++) {
newMap= list.get(j);
if(bigtypes.equals(newMap.get("bigtypes").toString())){//key值相等的:value相加
b++;
newList.remove(j);
Map<String, String> maMap2 = new HashMap<String, String>();
maMap2.put("bigtypes", bigtypes);
int xx= Integer.parseInt(newMap.get("num"))+Integer.parseInt(num);
maMap2.put("num",xx+"" );
newList.add(maMap2);
break;
}
}
if(b==0){//key值与list<map>的map无共同key的:list新增
newList.add(maMap);
}
list= newList;
}else{//只有一组数据
list.add(maMap);
}
} }
//取百分比
newList=new ArrayList();
for (int c = 0; c < list.size(); c++) {
Map<String,String> newMap2 =new HashMap<String, String>();
Map<String,String> oldmap=new HashMap<String, String>();
oldmap = list.get(c);
newMap2.put("bigtypes", oldmap.get("bigtypes"));
int aa= Integer.parseInt(oldmap.get("num"));
newMap2.put("num",towNumDivide(aa,talls)+"%");
newList.add(newMap2);
}
list=newList;
}