需求:有多个list,将多个list根据相同的时间和ID进行合并求交集。
例如:
list1 = [{"dateTime": "2020-04","id": "4","overdueRechargeTotal": 0,"overdueSurplusTotal": 0,"rechargeTotal": 0,"surplusTotal": 0,"totalCount": 0
},
{"dateTime": "2020-04","id": "3","overdueRechargeTotal": 0,"overdueSurplusTotal": 0,"rechargeTotal": 0,"surplusTotal": 0,"totalCount": 0
}]
list2=[{"dateTime": "2020-04","id": "3","totalCount": 10},{"dateTime": "2020-03","id": "3","totalCount": 10}]
合并后的结果是:
result = [{"dateTime": "2020-04","id": "4","overdueRechargeTotal": 0,"overdueSurplusTotal": 0,"rechargeTotal": 0,"surplusTotal": 0,"totalCount": 0
},
{"dateTime": "2020-04","id": "3","overdueRechargeTotal": 0,"overdueSurplusTotal": 0,"rechargeTotal": 0,"surplusTotal": 0,"totalCount": 10
},
{"dateTime": "2020-03","id": "3","overdueRechargeTotal": 0,"overdueSurplusTotal": 0,"rechargeTotal": 0,"surplusTotal": 0,"totalCount": 10
}]
完整代码
public class UsedDate {
private String id;
private String dateTime;
private String saleName;
private Integer totalCount;
private Integer rechargeTotal;
private Integer overdueRechargeTotal;
private Integer overdueSurplusTotal;
private Integer surplusTotal;
//get set 略……
}
List<UsedDate> parent = new ArrayList<>();
List<UsedDate> child = new ArrayList<>();
UsedDate user1 = new UsedDate("1","2020-04",0,0,0,0,0);
UsedDate user2 = new UsedDate("2","2020-04",0,0,0,0,0);
UsedDate user3 = new UsedDate("3","2020-04",0,0,0,0,0);
UsedDate user4 = new UsedDate("4","2020-04",0,0,0,0,0);
parent.add(user1);
parent.add(user2);
parent.add(user3);
parent.add(user4);
UsedDate child1 = new UsedDate("1","2020-02",10);
UsedDate child2 = new UsedDate("1","2020-03",11);
UsedDate child3 = new UsedDate("1","2020-04",10);
UsedDate child4 = new UsedDate("3","2020-03",10);
UsedDate child5 = new UsedDate("3","2020-04",10);
UsedDate child6 = new UsedDate("3","2020-01",10);
child.add(child1);
child.add(child2);
child.add(child3);
child.add(child4);
child.add(child5);
child.add(child6);
Map<String,UsedDate> map = new LinkedHashMap<>();
for(UsedDate p : parent){
if (map.containsKey(p.getId()+"|"+p.getDateTime())) {
map.get(p.getId()+"|"+p.getDateTime()).setTotalCount(p.getTotalCount());
map.get(p.getId()+"|"+p.getDateTime()).setOverdueRechargeTotal(p.getOverdueRechargeTotal());
map.get(p.getId()+"|"+p.getDateTime()).setOverdueSurplusTotal(p.getOverdueSurplusTotal());
map.get(p.getId()+"|"+p.getDateTime()).setSurplusTotal(p.getSurplusTotal());
map.get(p.getId()+"|"+p.getDateTime()).setRechargeTotal(p.getRechargeTotal());
}
map.put(p.getId()+"|"+p.getDateTime(),p);
}
for(UsedDate c : child) {
if (map.containsKey(c.getId()+"|"+c.getDateTime())) {
map.get(c.getId()+"|"+c.getDateTime()).setTotalCount(c.getTotalCount());
}
map.put(c.getId()+"|"+c.getDateTime(),c);
}
System.out.println(JSONObject.toJSONString(map.values()));
欢迎各位大佬留言更多跟快的方式,合并为空补0方法略过