List<Map<String, Integer>> 同key的value全部累加合並
阿新 • • 發佈:2018-08-10
print src add pan 圖片 int 技術分享 .get name
public static void main(String[] args){ List<Map<String,Object>> list1 = new ArrayList<Map<String,Object>>(); Map<String,Object> map1 = new HashMap<String,Object>(); Map<String,Object> map2 = new HashMap<String,Object>(); Map<String,Object> map3 = new HashMap<String,Object>(); map1.put("張三", new Integer(92)); map2.put("李四", new Integer(85)); map3.put("張三", new Integer(90)); list1.add(map1); list1.add(map2); list1.add(map3); Map<String,Object> mapAll = new HashMap<String,Object>(); for(Map<String,Object> map:list1){ for(Map.Entry<String, Object> entry:map.entrySet()){ String name = entry.getKey(); Object score = entry.getValue(); Object scoreAll = mapAll.get(entry.getKey()); if(scoreAll == null){ mapAll.put(name, score); }else{ scoreAll = new Integer((((Integer)scoreAll).intValue() + ((Integer)score).intValue())); mapAll.put(name, scoreAll); } } } for(Map.Entry<String, Object> entry:mapAll.entrySet()){ //如果需要將map再做list,在這裏處理 System.out.println(entry.getKey() + "," + entry.getValue()); } }
List<Map<String, Integer>> 同key的value全部累加合並