业务场景:前端返回的数据,需要对比进行增删改操作
public class FilterCompare<T> {
private final List<T> intersectionList ;
private final List<T> unionList ;
private final List<T> differenceList ;
private final List<T> complenmentList ;
private FilterCompare(List<T> intersection, List<T> union, List<T> difference, List<T> complenment){
this.intersectionList = intersection;
this.unionList = union;
this.differenceList = difference;
this.complenmentList = complenment;
}
private FilterCompare(){
this.intersectionList = new ArrayList<>();
this.unionList = new ArrayList<>();
this.differenceList = new ArrayList<>();
this.complenmentList = new ArrayList<>();
}
public static <T, R> FilterCompare<T> getInstance(List<T> original, List<T> compare, Function<T, R> fun) {
if(original.isEmpty() && compare.isEmpty()){
return new FilterCompare<>();
}
List<T> intersection = original.stream().filter(i-> compare.stream().map(fun).collect(Collectors.toList()).contains(fun.apply(i))).collect(Collectors.toList());
List<T> difference = original.stream().filter(i-> !compare.stream().map(fun).collect(Collectors.toList()).contains(fun.apply(i))).collect(Collectors.toList());
List<T> complenment = compare.stream().filter(i-> !original.stream().map(fun).collect(Collectors.toList()).contains(fun.apply(i))).collect(Collectors.toList());
original.addAll(compare);
return new FilterCompare<>(intersection, original,difference,complenment);
}
//交集
public List<T> getIntersection(){
return this.intersectionList;
}
//并集
public List<T> getUnion(){
return this.unionList;
}
//差集
public List<T> getDifference(){
return this.differenceList;
}
//补集
public List<T> getComplement(){
return this.complenmentList;
}
调用
FilterCompare<UpBean> filterCompare = FilterCompare.getInstance
(mobileUpBeanList, UpBeans, UpBean::getId);
List<UpBean> updateListByMobile = filterCompare.getIntersection();
List<UpBean> addListByMobile= filterCompare.getDifference();
List<UpBean> delListByMobile= filterCompare.getComplement();
bridgeUpDao.update(updateListByMobile);
bridgeUpDao.insert(addListByMobile);
bridgeUpDao.deleteBy(delListByMobile);
log.info("[Id:{},app新增: {}条,修改 {}条,删除{}条, 消耗时间:{}]",
Id, addListByMobile.size(), updateListByMobile.size(), delListByMobile.size(),
(System.currentTimeMillis() - st) / 1000.0);
}