博客
关于我
List<Map>遍历修改map值
阅读量:802 次
发布时间:2023-02-05

本文共 2057 字,大约阅读时间需要 6 分钟。

    

有一个测试方法需要实现:

测试方法test2的实现步骤如下:

步骤一:初始化数据

首先,创建一个用于存储历史数据的列表historyList:

historyList初始化为三个map对象,每个map包含两个键值对:levels和counts:

        List
> historyList = new ArrayList<>(); for(int i = 0; i < 3; i++) { Map
tempMap = new HashMap<>(); tempMap.put("levels", String.valueOf(i+1)); tempMap.put("counts", "0"); historyList.add(tempMap); }

步骤二:创建临时列表

接下来,创建一个临时列表tempList,用于存储需要更新的数据:

        List
> tempList = new ArrayList<>(); for(int i = 0; i < 2; i++) { Map
tempMap = new HashMap<>(); tempMap.put("levels", String.valueOf(i+1)); tempMap.put("counts", i+5); tempList.add(tempMap); }

步骤三:更新历史数据

遍历tempList中的每个map,检查是否有与historyList中相同的levels值:

        if(tempList.size() > 0) {            for (Map
map : historyList) { String key = String.valueOf(map.get("levels")); String value = String.valueOf(map.get("counts")); for (Map
tempmap : tempList) { String tempkey = String.valueOf(tempmap.get("levels")); String tempvalue = String.valueOf(tempmap.get("counts")); if(tempkey.equals(key)) { value = tempvalue; break; } } map.put("counts", value); } }

步骤四:计算总和

最后,计算tempList中所有counts值的总和:

        int upcount = 0;        for (Map
map : tempList) { upcount += Integer.parseInt(String.valueOf(map.get("counts"))); } System.out.println(upcount);

输出结果如下:

        System.out.println("tempList: " + tempList.toString());        System.out.println("historyList: " + historyList.toString());    

转载地址:http://pzufk.baihongyu.com/

你可能感兴趣的文章
mysql 四种存储引擎
查看>>
MySQL 在并发场景下的问题及解决思路
查看>>
MySQL 在控制台插入数据时,中文乱码问题的解决
查看>>
MySQL 基础架构
查看>>
MySQL 基础模块的面试题总结
查看>>
MySQL 处理插入重主键唯一键重复值办法
查看>>
MySQL 备份 Xtrabackup
查看>>
mysql 复杂查询_mysql中复杂查询
查看>>
mYSQL 外键约束
查看>>
mysql 多个表关联查询查询时间长的问题
查看>>
mySQL 多个表求多个count
查看>>
mysql 多字段删除重复数据,保留最小id数据
查看>>
MySQL 多表联合查询:UNION 和 JOIN 分析
查看>>
MySQL 大数据量快速插入方法和语句优化
查看>>
mysql 如何给SQL添加索引
查看>>
mysql 字段区分大小写
查看>>
mysql 字段合并问题(group_concat)
查看>>
mysql 字段类型类型
查看>>
MySQL 字符串截取函数,字段截取,字符串截取
查看>>
MySQL 存储引擎
查看>>