求写下代码,并每行添加注释
问题描述:
/*
请用代码将list2中的score合并到List中(如果匹配不到则用"-"代替)
*/
package test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Exercise {
public static void main(String[] args) {
List<Map<String,String>> list1=new ArrayList<>();
List<Map<String,String>> list2=new ArrayList<>();
Map<String,String>map;
map=new HashMap<>();
map.put("id","1");
map.put("name","张三");
list1.add(map);
map=new HashMap<>();
map.put("id","2");
map.put("name","李四");
list1.add(map);
map=new HashMap<>();
map.put("id","3");
map.put("name","王五");
list1.add(map);
map=new HashMap<>();
map.put("id","2");
map.put("score","90");
list2.add(map);
map=new HashMap<>();
map.put("id","3");
map.put("score","88");
list2.add(map);
map=new HashMap<>();
map.put("id","4");
map.put("score","75");
list2.add(map);
//todo 从这里开始
}
}
答
我是这样理解题干的,如果list1里面的id和list2里面的id相同,则更新list1里面的score,代码如下,时间仓促,写的有点着急:
public static void main(String[] args) {
List<Map<String,String>> list1=new ArrayList<>();
List<Map<String,String>> list2=new ArrayList<>();
Map<String,String>map;
map=new HashMap<>();
map.put("id","1");
map.put("name","张三");
list1.add(map);
map=new HashMap<>();
map.put("id","2");
map.put("name","李四");
list1.add(map);
map=new HashMap<>();
map.put("id","3");
map.put("name","王五");
list1.add(map);
map=new HashMap<>();
map.put("id","2");
map.put("score","90");
list2.add(map);
map=new HashMap<>();
map.put("id","3");
map.put("score","88");
list2.add(map);
map=new HashMap<>();
map.put("id","4");
map.put("score","75");
list2.add(map);
//todo 从这里开始
for(Map<String,String> map1:list1){
for(Map.Entry<String, String> entry1:map1.entrySet()){
if ("id".equals(entry1.getKey())){
boolean bool=false;
String score="";
for (Map<String,String> map2:list2){
for(Map.Entry<String, String> entry:map2.entrySet()){
if ("id".equals(entry.getKey()) && entry1.getValue().equals(entry.getValue())){
bool=true;
}
}
if (bool){
score = map2.get("score");
break;
}else{
score="-";
}
}
map1.put("score",score);
}
}
}
list1.forEach(l->{
System.out.println("===================================>");
l.forEach((k,v)->{
System.out.println("k:"+k+",v:"+v);
});
System.out.println("===================================>");
});
}
打印list1集合结果如下: