JAVA基础----两个List
public static void main(String[] args) {
List<Map<String,Object>> list1 = new ArrayList<>();
List<Map<String,Object>> list2 = new ArrayList<>();
List<Map<String,Object>> list3 = new ArrayList<>();
for(int i = 1 ; i < 30000; i++){
Map<String,Object> map = new HashMap<>();
map.put("barCode",i);
map.put("key1","1");
map.put("key2","1");
list2.add(map);
}
for(int i = 1 ; i < 80000; i++){
Map<String,Object> map = new HashMap<>();
map.put("barCode",i);
map.put("itemId","1");
map.put("itemFeatureId","1");
list1.add(map);
}
//list1和list2要比较,使用的字段是barCode
list3 = different(list1,list2);
System.out.println(list3.size());
list3 = different1(list1,list2);
System.out.println(list3.size());
}
方法1:遍历list2(元素少的list),将两个list可以唯一校验的字段存为map的key。遍历list1(元素多的list),判断list1中的key是否在map中存在。
遍历次数为:list1.size()+list2.size()
public static List<Map<String,Object>> different(List<Map<String,Object>> list1,List<Map<String,Object>> list2) {
long start = System.currentTimeMillis();
Map<String, Integer> map = new HashMap<String, Integer>(list1.size() + list2.size());
for (Map<String,Object> minMap :list2) {
map.put(minMap.get("barCode").toString(), 1);
}
Iterator<Map<String,Object>> it = list1.iterator();
while(it.hasNext()){
Map<String,Object> pickMap = it.next();
if(map.containsKey(pickMap.get("barCode").toString())){
it.remove();
}
}
System.out.println("方法1 耗时:" + (System.currentTimeMillis() - start) + " 毫秒");
return list1;
}
方法2:两层遍历查找,遍历次数为list1.size()*list2.size()
public static List<Map<String,Object>> different1(List<Map<String,Object>> list1,List<Map<String,Object>> list2) {
long start = System.currentTimeMillis();
List<Map<String,Object>> list= new ArrayList<>();
for (Map<String, Object> map1 : list1) {
boolean flag = true;
for (Map<String, Object> map2 : list2) {
if(map1.get("barCode").equals(map2.get("barCode"))){
flag = false;
}
}
if(flag){
list.add(map1);
}
}
System.out.println("方法2 耗时:" + (System.currentTimeMillis() - start) + " 毫秒");
return list;
}
对于数据少的时候两者耗时差不多。对于数据量大的,方法一明显优于方法二。