获取差集数据(比较两个集合、获取需要新增或删除的数据)
最近遇到一个企业微信对接需求 其中有一个 接口是 获取客户群详情 ,里面有群成员,由于每次都是给的全部,需要和数据库存的进行对比差异(多了或少了某个人)
/**
* 可直接复制运行
*
/**
* oldData.add(new Student("a"));
* oldData.add(new Student("del"));
* oldData.add(new Student("del1"));
* oldData.add(new Student("del2"));
*
* newData.add(new Student("a"));
* newData.add(new Student("c"));
* newData.add(new Student("add"));
* newData.add(new Student("add11"));
*
* 输出:以下是需要删除的数据2
* delData:del
* delData:del1
* delData:del2
* ===========
* 以下是需要添加的数据2
* addData:c
* addData:add
* addData:add11
*/
*
*/
public static void main(String[] args) throws Exception {
// reversePrint();
getDifferentData();
}
/**
* 获取差集数据
* 需要新增和删除的数据
*/
public static void getDifferentData() throws Exception {
List<Student >oldData=new ArrayList<>();
for (int i=0;i<100000;i++){
oldData.add(new Student("a"+i));
}
oldData.add(new Student("a"));
oldData.add(new Student("del"));
oldData.add(new Student("del1"));
oldData.add(new Student("del2"));
List<Student >newData=new ArrayList<>();
for (int i=0;i<100000;i++){
newData.add(new Student("a"+i));
}
newData.add(new Student("a"));
newData.add(new Student("c"));
newData.add(new Student("add"));
newData.add(new Student("add11"));
// List<Student >addList=new ArrayList<>(list2);
long start=System.currentTimeMillis();
//获取到需要删除的差集
List<Student> delList = removeAll(oldData,newData,Student::getId);
List<Student> addList= removeAll(newData,oldData,Student::getId);
System.out.println("执行耗时:"+(System.currentTimeMillis()-start)+"ms");
System.out.println("以下是需要删除的数据");
for (Student s : delList) {
System.out.println("delData:"+s.getId());
}
System.out.println("===========\n");
System.out.println("以下是需要添加的数据");
for (Student s : addList) {
System.out.println("addData:"+s.getId());
}
System.out.println("===========到底了===========");
}
/**
* 差集:删除左边集合中在右边集合存在的元素并返回
* @param left
* @param right
* @return
*/
public static <T,R> List<T> removeAll(List<T> left, List<T> right, Function<T, R> fun) throws Exception {
if (left == null){
return null;
}
if (right == null){
return left;
}
Set<R> set = new HashSet<>();
//使用LinkedList方便插入和删除
List<T> res = new LinkedList<>(left);
for(T item : right){
set.add(fun.apply(item));
}
//如果set中包含id则remove
res.removeIf(item -> set.contains(fun.apply(item)));
return res;
}
public static class Student implements Serializable {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String id) {
this.id = id;
}
public Student() {
}
}
2021年7月2日 修改 不指定具体泛型,取消反射调用,感谢卢老师的帮助 @https://blog.csdn.net/weixin_43745366?spm=1001.2014.3001.5512