我们在对一个实体进行编辑的时候,可能会遇到以下问题:这个实体以前含有某些值,现在修改成其他值,前后的值有重叠的部分。比如
在编辑属性集的时候,需要维护attr_set_sku表,有两种方法:
1.先删除原来set_id的记录,再插入现在的sku_id(多个)和set_id。
2.比较前后两次set_id的不一样,看做两个集合:前者为c1,后者为c2,那么现在的操作就变为:插入c2-c1,删除c1-c2。-表示两个集合的差。重叠的即
c1&c2的部分就不用变,如此如果前后变化不大,操作的数据量就非常少,尤其在记录比较多的情况下效果更明显。
以下是一个工具类,提供集合的交并差功能。
/**
* 提供集合的交并差功能。
*/
public class CollectionOperator<E> {
Collection<E> opt1;
Collection<E> opt2;
Collection<E> result;
/**
* 用于操作的两个集合
*/
public CollectionOperator(Collection<E> opt1, Collection<E> opt2){
if(opt1 == null || opt2 == null){
throw new RuntimeException("请填写非空集合!");
}
this.opt1 = opt1;
this.opt2 = opt2;
result = new HashSet<E>();// 这里不能使用ArrayList<>(),否则求并集就可能会有重复的
}
/**
* 集合交
*/
public Collection<E> intersect(){
result.clear();
result.addAll(opt1);
result.retainAll(opt2);
return result;
}
/**
* 集合并
*/
public Collection<E> union(){
result.clear();
result.addAll(opt1);
result.addAll(opt2);
return result;
}
/**
* 集合差
*/
public Collection<E> diff(){
result.clear();
result.addAll(opt1);
result.removeAll(opt2);
return result;
}
public static void main(String[] args){
List<Integer> opt1 = new ArrayList<Integer>();
opt1.add(1);
opt1.add(2);
opt1.add(3);
opt1.add(4);
Set<Integer> opt2 = new HashSet<Integer>();
opt2.add(3);
opt2.add(4);
opt2.add(5);
opt2.add(6);
CollectionOperator<Integer> co = new CollectionOperator<Integer>(opt1, opt2);
System.out.println(co.intersect());
System.out.println(co.union());
System.out.println(co.diff());
}
}