List<Map>遍历修改map值

有个小需求:

list2 覆盖 list1 对应的值, 无对应时默认list的值,(list1.size()大于list2,只是counts 值不同)
list1 [{levels=1, counts=0}, {levels=2, counts=0}, {levels=3, counts=0}]
list2 [{levels=1, counts=2}, {levels=3, counts=12}]
结果: list1 [{levels=1, counts=2}, {levels=2, counts=0}, {levels=3, counts=12}]

	@Test
	public void test2() {
		//模拟数据
		List<Map<String, Object>> historyList = new ArrayList<Map<String,Object>>();
		for(int i = 0; i < 3; i++) {
			Map<String, Object> tempMap = new HashMap<>();
			tempMap.put("levels", String.valueOf(i+1));
			tempMap.put("counts", "0");
			historyList.add(tempMap);
		}
		System.out.println("historyList: "+ historyList.toString()); 
		
		List<Map<String, Object>> tempList = new ArrayList<Map<String,Object>>();
		for(int i = 0; i < 2; i++) {
			Map<String, Object> tempMap = new HashMap<>();
			tempMap.put("levels", String.valueOf(i+1));
			tempMap.put("counts", i+5);
			tempList.add(tempMap);
		}
		//修改值
		if(tempList.size() > 0) {
			for (Map<String, Object> map : historyList) {
				String key = String.valueOf(map.get("levels"));
				String value = String.valueOf(map.get("counts"));
				for (Map<String, Object> 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);
			}
			int upcount = 0;
			for (Map<String, Object> 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()); 
	}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值