Java List<Map>集合根据相同key分组进行某项数据求和
Posted java李杨勇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java List<Map>集合根据相同key分组进行某项数据求和相关的知识,希望对你有一定的参考价值。
package com.yt.exam.ctrl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by LiYangYong
*/
public class test
public static void main(String[] args)
List<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> map1 = new HashMap<>();
map1.put("userId", "120");
map1.put("value", 111);
list.add(map1);
Map<String, Object> map2 = new HashMap<>();
map2.put("userId", "120");
map2.put("value", 112);
list.add(map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("userId", "110");
map3.put("value", 2022);
list.add(map3);
Map<String, Object> map4 = new HashMap<>();
map4.put("userId", "110");
map4.put("value", 56);
list.add(map4);
Map<String, Object> map5 = new HashMap<>();
map5.put("userId", "159");
map5.put("value", 2022);
list.add(map5);
System.out.println("统计后的数据--->>>"+list);
//根据userId key 合计value
Map<String, Map<String, Object>> result = new HashMap<>();
List<Map<String, Object>> allList = new ArrayList<>();
for(Map<String, Object> map : list)
String newId = map.get("userId").toString();
Integer value = Integer.parseInt(map.get("value").toString());
if(result.containsKey(newId))
Integer temp = Integer.parseInt(result.get(newId).get("value").toString());
value += temp;
result.get(newId).put("value", value);
continue;
result.put(newId, map);
allList.add(map);
System.out.println("");
System.out.println("统计后的数据--->>>"+allList);
测试结果如下:
以上是关于Java List<Map>集合根据相同key分组进行某项数据求和的主要内容,如果未能解决你的问题,请参考以下文章