博客
关于我
List<Map>遍历修改map值
阅读量:792 次
发布时间: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/

你可能感兴趣的文章
Linux:安装Nginx
查看>>
Linux:安装npm
查看>>
Linux:安装Redis
查看>>
Linux:安装ruby
查看>>
Linux:安装rvm
查看>>
Linux:服务器监控神器Netdata
查看>>
lirs cache java库_Java 缓存库 — Caffeine
查看>>
list extend() 索引,不仅将列表元素插入到末尾
查看>>
List GroupBy真实用法,Reflection(反射)用法,Enum用法,正则,搜索下拉布局
查看>>
list set map的区别
查看>>
List 去重的 6 种方法,这个方法最完美
查看>>
List 去重的 6 种方法,这个方法最完美!
查看>>
List 集合去重的 3 种方法
查看>>
List,Set,Map三者的区别(不同点)
查看>>
list.pop 的 numpy 等效项?
查看>>
list.remove()时报java.lang.UnsupportedOperationException异常错误的处理
查看>>
list.size()和list.isEmpty()的区别和效率以及CollectionUtils.isEmpty()的使用
查看>>
List<Map>遍历修改map值
查看>>
List<T> to DataTable
查看>>
ListBox 循环删除当前项
查看>>