有个小需求:
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());
}
结果: