博客
关于我
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/

你可能感兴趣的文章
python中的@staticmethod
查看>>
python中的array函数作用_NumPy 数组使用大全
查看>>
python中的isinstance判断多个对象类型
查看>>
python中的keys、values、items
查看>>
Python中的lambda和apply结合使用
查看>>
python中的map函数
查看>>
Python中的numpy模块解析
查看>>
Python中的pickle
查看>>
Python中的signal模块和Ctrl+C操作
查看>>
python中的sort方法
查看>>
Python中的threading
查看>>
python中的urlencode和urldecode
查看>>
python中的with学习
查看>>
python中的write和read的用法,有无换行符
查看>>
Python中的“真“和“假“
查看>>
PYTHON中的主体对象标识
查看>>
Python中的修饰函数始终返回NONE
查看>>
Python中的元素相乘与矩阵相乘(附Demo)
查看>>
Python中的分组/聚类数字
查看>>
python中的十六进制字符串到字节数组
查看>>