您当前的位置: 首页 > 

Charge8

暂无认证

  • 3浏览

    0关注

    447博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

List遍历修改map值

Charge8 发布时间:2018-12-04 16:11:09 ,浏览量:3

有个小需求:

        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 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);
		}
		System.out.println("historyList: "+ historyList.toString()); 
		
		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);
		}
		//修改值
		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);
			}
			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()); 
	}

      

    结果:

     

 

 

 

 

 

关注
打赏
1664721914
查看更多评论
立即登录/注册

微信扫码登录

0.0401s