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

本文共 2092 字,大约阅读时间需要 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/

你可能感兴趣的文章
OAuth 2.0 MAC Tokens
查看>>
OAuth 及 移动端鉴权调研
查看>>
OAuth2 + Gateway统一认证一步步实现(公司项目能直接使用),密码模式&授权码模式
查看>>
OAuth2 Provider 项目常见问题解决方案
查看>>
OAuth2 vs JWT,到底怎么选?
查看>>
Vue.js 学习总结(14)—— Vue3 为什么推荐使用 ref 而不是 reactive
查看>>
oauth2-shiro 添加 redis 实现版本
查看>>
OAuth2.0_JWT令牌-生成令牌和校验令牌_Spring Security OAuth2.0认证授权---springcloud工作笔记148
查看>>
OAuth2.0_JWT令牌介绍_Spring Security OAuth2.0认证授权---springcloud工作笔记147
查看>>
OAuth2.0_介绍_Spring Security OAuth2.0认证授权---springcloud工作笔记137
查看>>
OAuth2.0_完善环境配置_把资源微服务客户端信息_授权码存入到数据库_Spring Security OAuth2.0认证授权---springcloud工作笔记149
查看>>
OAuth2.0_授权服务配置_Spring Security OAuth2.0认证授权---springcloud工作笔记140
查看>>
OAuth2.0_授权服务配置_三项内容_Spring Security OAuth2.0认证授权---springcloud工作笔记141
查看>>
OAuth2.0_授权服务配置_令牌服务和令牌端点配置_Spring Security OAuth2.0认证授权---springcloud工作笔记143
查看>>
OAuth2.0_授权服务配置_客户端详情配置_Spring Security OAuth2.0认证授权---springcloud工作笔记142
查看>>
OAuth2.0_授权服务配置_密码模式及其他模式_Spring Security OAuth2.0认证授权---springcloud工作笔记145
查看>>
OAuth2.0_授权服务配置_授权码模式_Spring Security OAuth2.0认证授权---springcloud工作笔记144
查看>>
OAuth2.0_授权服务配置_资源服务测试_Spring Security OAuth2.0认证授权---springcloud工作笔记146
查看>>
OAuth2.0_环境介绍_授权服务和资源服务_Spring Security OAuth2.0认证授权---springcloud工作笔记138
查看>>
OAuth2.0_环境搭建_Spring Security OAuth2.0认证授权---springcloud工作笔记139
查看>>