补集一般指绝对补集,即一般地,设S是一个集合,A是S的一个真子集,由S中所有不属于A的元素组成的集合,叫做子集A在S中的绝对补集(简称补集或余集)。
程序中的补集一般用于比较数据差异。
比如:云同步手机联系人
手机端 云端
张三 10010 张三 10013
李四 10011 王八 10016
王五 10012 李四 10011
在大数据量的情况下,我们可能需要程序过滤出差异数据好进行数据同步。
相对补集
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
List> l_m1 = new ArrayList>();
Map map1=new HashMap();
map1.put("id", "1");
map1.put("hash", "10086");
Map map2=new HashMap();
map2.put("id", "2");
map2.put("hash", "10087");
Map map3=new HashMap();
map3.put("id", "3");
map3.put("hash", "10088");
Map map8=new HashMap();
map8.put("id", "8");
map8.put("hash", "88888");
l_m1.add(map1);
l_m1.add(map2);
l_m1.add(map3);
l_m1.add(map8);
List> l_m2 = new ArrayList>();
Map map4=new HashMap();
map4.put("id", "4");
map4.put("hash", "10089");
Map map5=new HashMap();
map5.put("id", "5");
map5.put("hash", "10090");
Map map6=new HashMap();
map6.put("id", "6");
map6.put("hash", "10091");
Map map9=new HashMap();
map9.put("id", "8");
map9.put("hash", "88888");
l_m2.add(map4);
l_m2.add(map5);
l_m2.add(map6);
l_m2.add(map9);
System.out.println(Test.retainAll(l_m1, l_m2).toString());;
}
public static Map retainAll(List> l1,List> l2){
List l1_h=new ArrayList();
Map> l1_h_m=new HashMap>();
List l2_h=new ArrayList();
Map> l2_h_m=new HashMap>();
for(int i=0;i
l1_h.add(i, l1.get(i).toString().hashCode());
l1_h_m.put(l1.get(i).toString().hashCode(),l1.get(i));
}
for(int i=0;i
l2_h.add(i, l2.get(i).toString().hashCode());
l2_h_m.put(l1.get(i).toString().hashCode(),l1.get(i));
}
l1_h.retainAll(l2_h);
for(Integer hash:l1_h){
l1_h_m.remove(hash);
}
for(Integer hash:l1_h){
l2_h_m.remove(hash);
}
List> rl1=new ArrayList>();
for(Map.Entry> entry : l1_h_m.entrySet()) {
rl1.add(entry.getValue());
}
List> rl2=new ArrayList>();
for(Map.Entry> entry : l2_h_m.entrySet()) {
rl2.add(entry.getValue());
}
Map rsm=new HashMap();
rsm.put("l1", rl1);
rsm.put("l2", rl2);
return rsm;
}
}
JAVA集合运算获得数据差异(补集)
猜你喜欢
转载自yzsy0818.iteye.com/blog/2205795
今日推荐
周排行