当前位置:网站首页>如何将List<Map>进行分组数值计算合并排序
如何将List<Map>进行分组数值计算合并排序
2022-08-09 14:51:00 【学弟不想努力了】
import java.util.*;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
//list模拟数据
Map map1 = new HashMap();
map1.put("shopId",1);
map1.put("salesmanId",2);
map1.put("money", 20);
Map map2 = new HashMap();
map2.put("shopId",2);
map2.put("salesmanId",2);
map2.put("money", 100);
Map map5 = new HashMap();
map5.put("shopId",2);
map5.put("salesmanId",2);
map5.put("money", 50);
List<Map> list1 = new ArrayList<>();
list1.add(map1);
list1.add(map2);
list1.add(map5);
// System.out.println(list1);
// [{salesmanId=2, money=20, shopId=1}, {salesmanId=2, money=100, shopId=2}, {salesmanId=2, money=50, shopId=2}]
//list<Map>分组,按超市分组
Map<String, List<Map>> mapGroup = list1.stream().collect(Collectors.groupingBy(o -> o.get("shopId") + ""));
// System.out.println(mapGroup);
// {1=[{salesmanId=2, money=20, shopId=1}], 2=[{salesmanId=2, money=100, shopId=2}, {salesmanId=2, money=50, shopId=2}]}
List<Map> listReturn = new ArrayList<>();
for (String str : mapGroup.keySet()) {
List<Map> task1 = mapGroup.get(str);
int money = 0;
for (Map mm: task1) {
money = money + Integer.valueOf(String.valueOf(mm.get("money")));
}
Map<String, Object> mapReturn = new HashMap();
mapReturn.put("shopId", task1.get(0).get("shopId"));
mapReturn.put("salesmanId", task1.get(0).get("salesmanId"));
mapReturn.put("money", money);
listReturn.add(mapReturn);
}
// System.out.println(listReturn);
// [{salesmanId=2, money=20, shopId=1}, {salesmanId=2, money=150, shopId=2}]
//根据money 倒叙排序
Collections.sort(listReturn, (o2, o1) -> {
Integer shop1 = Integer.valueOf(o1.get("shopId").toString());
Integer shop2 = Integer.valueOf(o2.get("shopId").toString());
return shop1.compareTo(shop2);
});
// System.out.println(listReturn);
// [{salesmanId=2, money=150, shopId=2}, {salesmanId=2, money=20, shopId=1}]
}
}
边栏推荐
猜你喜欢

由于谷歌版本自动更新,导致selenium项目报错,如何关闭谷歌浏览器的自动更新?

C语言程序设计笔记(浙大翁恺版) 第二周:计算

防汛添利器,数字技术筑起抗洪“大堤”

百度地图——鹰眼轨迹服务

网站授权QQ登录

C语言程序设计笔记(浙大翁恺版) 第八周:数组

暴雨天,看天翼云如何“快准稳”防涝

C语言程序设计笔记(浙大翁恺版) 第十二周:程序结构

Startup error: Caused by: org.apache.ibatis.binding.BindingException summary solution

MySQL principle and optimization: Limit the query optimization
随机推荐
redis从入门到精通
6大论坛,30+技术干货议题,2022首届阿里巴巴开源开放周来了!
DMPE-PEG-Mal Maleimide-PEG-DMPE dimyristoylphosphatidylethanolamine-polyethylene glycol-maleimide
Common sql records
[LeetCode] 485.最大连续 1 的个数
OpenSSF的开源软件风险评估工具:Scorecards
MySQL学习笔记
和月薪5W的测试聊过后,才知道自己一直在打杂...
Two-dimensional array to realize the eight queens problem
听书项目总结
OpenCV - 矩阵操作 Part 3
防汛添利器,数字技术筑起抗洪“大堤”
JS——循环结构经典例题解析与分享
C语言程序设计笔记(浙大翁恺版) 第一周:程序设计与C语言
Docker安装Redis详细步骤
xshell7连接工具下载
OpenCV笔记整理【视频处理】
[Serilog] Simple .NET logging with fully structured events
What is the difference between the four common resistors?
Grad CAM 模型可视化