CollectionUtils.intersection

CollectionUtils.intersection

CollectionUtils.intersection

  • 今天看了下公司的同事的代码,发现中间有使用

  •    Collection<String> intersection = CollectionUtils.intersection(a, b); 
    
  • 简单看了一下源码,网上也了解到是取集合的交集,但是有一个小坑的地方,需要注意,源码如下:

  •     public static Collection intersection(final Collection a, final Collection b) {
            ArrayList list = new ArrayList();
            Map mapa = getCardinalityMap(a);
            Map mapb = getCardinalityMap(b);
            Set elts = new HashSet(a);
            elts.addAll(b);
            Iterator it = elts.iterator();
            while(it.hasNext()) {
                Object obj = it.next();
                for(int i=0,m=Math.min(getFreq(obj,mapa),getFreq(obj,mapb));i<m;i++) {
                    list.add(obj);
                }
            }
            return list;
        }
    
  • getCardinalityMap 方法将集合转换为Map,key为实例,value为出现的次数

  • public static Map getCardinalityMap(final Collection coll) {
        Map count = new HashMap();
        for (Iterator it = coll.iterator(); it.hasNext();) {
            Object obj = it.next();
            Integer c = (Integer) (count.get(obj));
            if (c == null) {
                count.put(obj,INTEGER_ONE);
            } else {
                count.put(obj,new Integer(c.intValue() + 1));
            }
        }
        return count;
    }
    
  • 那么将两个集合分别转换为这样的一个Map,两个集合一起存在Set中,遍历Set,getFreq()就是获取该对象出现次数,那么就会出现Math.min得出在两个集合中都出现的最少的次数,会大于1,这时候输出的集合中,也会出现这么多次数,于是我验证了一下

  • public static void main(String[] args) {
        String[] arrayA = new String[] { "1", "2", "3", "3","3", "4", "5" };
        String[] arrayB = new String[] { "3", "4", "4", "5", "6","3", "7" ,"3" , "3" };
        List<String> a = Arrays.asList(arrayA);
        List<String> b = Arrays.asList(arrayB);
        Collection<String> intersection = CollectionUtils.intersection(a, b);
        System.out.println( ArrayUtils.toString(intersection.toArray()));
    }
    
  • 结果

  • {3,3,3,5,4}
    
  • 因为3在集合 arrayA 中中出现3次,集合 arrayB 出现4 次,那么最终会遍历出现3次。如果源码 while 中这样改一下,就不会重复了

  •     while(it.hasNext()) {
            Object obj = it.next();
            if (Math.min(getFreq(obj,mapa),getFreq(obj,mapb)) > 0){
                list.add(obj);
            }
        }
    
  • 那么输出结果就是

  • {3,5,4}
    
    
  • 或者我们接收的时候转换为Set也可以达到去重的效果。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT枫斗者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值