一个工具类-----集合的交并差

我们在对一个实体进行编辑的时候,可能会遇到以下问题:这个实体以前含有某些值,现在修改成其他值,前后的值有重叠的部分。比如

在编辑属性集的时候,需要维护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());
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值