一个Integer型的list1集合,元素为{2017,2018,2019,2020}
一个<String,Integer>Map型的list2集合{{“year”:2019,”well”:22},{“year”:2020,”well”:33}}
现在要求按照list1元素位置及个数,补全数据,比如list1中有2017,2018年份,但是没有数据,将2017,2018年按照list2中数据格式,放到lsit2中
① 首先将list2中的年份(2019,2020)放在一个Set集合中;
② 定义一个索引index,初始值为-1;
③ For循环遍历集合list1,循环取出元素(2017,2018,2019,2020)
④ 判断Set集合中是否包含list1中的元素,若包含则跳出循环,否则,创建一个Map,将不包含的年份设置到map中,将well设置为0,最后将这个map按照index索引添加到Map型的list集合;
public static void main(String[] args) {
List<Integer> list1 = Lists.newArrayList(2017, 2018, 2019, 2020);
List<Map<String,Integer>> list2 = Lists.newArrayList(new HashMap<String,Integer>(){
{put("year", 2017); put("well", 2017);}
},new HashMap<String,Integer>(){
{put("year", 2020); put("well", 2020);}
});
Set<Object> set2 = new HashSet<>();
for(Map el2:list2){
set2.add(el2.get("year"));
}
int index = -1;
for (int i = 0;i < list1.size();i++){
Integer integer = list1.get(i);
index ++;
if(set2.contains(integer)){
continue;
}else{
Map<String, Integer> hashMap = new HashMap<String, Integer>() {{
put("year", integer);
put("well", 0);
}};
list2.add(index,hashMap);
}
}
System.out.println(list2);
//[{year=2017, well=2017}, {year=2018, well=0}, {year=2019, well=0}, {year=2020, well=2020}]
}