博客
关于我
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-2019-4-21-复习
查看>>
mysql-5.6.17-win32免安装版配置
查看>>
mysql-5.7.18安装
查看>>
MySQL-8.0.16 的安装与配置
查看>>
MySQL-Buffer的应用
查看>>
mysql-cluster 安装篇(1)---简介
查看>>
mysql-connector-java.jar乱码,最新版mysql-connector-java-8.0.15.jar,如何愉快的进行JDBC操作...
查看>>
mysql-connector-java各种版本下载地址
查看>>
mysql-EXPLAIN
查看>>
MySQL-Explain的详解
查看>>
mysql-group_concat
查看>>
MySQL-redo日志
查看>>
MySQL-【1】配置
查看>>
MySQL-【4】基本操作
查看>>
Mysql-丢失更新
查看>>
Mysql-事务阻塞
查看>>
Mysql-存储引擎
查看>>
mysql-开启慢查询&所有操作记录日志
查看>>
MySQL-数据目录
查看>>