java判断集合是否存在交集

一、jdk1.8以下版本

1、Collections.disjoint()

1.1、方法在java.util包中。

1.2、用于检查给定的 Collection 对象是否可能包含任何公共元素;不存在公共元素时返回true,否则返回false。

 public static boolean disjoint(Collection cl1, Collection cl2);

1.3、代码块

public static boolean disjoint(Collection<?> c1, Collection<?> c2) {
        // The collection to be used for contains(). Preference is given to
        // the collection who's contains() has lower O() complexity.
        Collection<?> contains = c2;
        // The collection to be iterated. If the collections' contains() impl
        // are of different O() complexity, the collection with slower
        // contains() will be used for iteration. For collections who's
        // contains() are of the same complexity then best performance is
        // achieved by iterating the smaller collection.
        Collection<?> iterate = c1;

        // Performance optimization cases. The heuristics:
        //   1. Generally iterate over c1.
        //   2. If c1 is a Set then iterate over c2.
        //   3. If either collection is empty then result is always true.
        //   4. Iterate over the smaller Collection.
        if (c1 instanceof Set) {
            // Use c1 for contains as a Set's contains() is expected to perform
            // better than O(N/2)
            iterate = c2;
            contains = c1;
        } else if (!(c2 instanceof Set)) {
            // Both are mere Collections. Iterate over smaller collection.
            // Example: If c1 contains 3 elements and c2 contains 50 elements and
            // assuming contains() requires ceiling(N/2) comparisons then
            // checking for all c1 elements in c2 would require 75 comparisons
            // (3 * ceiling(50/2)) vs. checking all c2 elements in c1 requiring
            // 100 comparisons (50 * ceiling(3/2)).
            int c1size = c1.size();
            int c2size = c2.size();
            if (c1size == 0 || c2size == 0) {
                // At least one collection is empty. Nothing will match.
                return true;
            }

            if (c1size > c2size) {
                iterate = c2;
                contains = c1;
            }
        }

        for (Object e : iterate) {
            if (contains.contains(e)) {
               // Found a common element. Collections are not disjoint.
                return false;
            }
        }

        // No common elements were found.
        return true;
    }

1.4、用法

    public static void main(String[] args) {
        List<Integer> aa = new ArrayList<>();
        aa.add(1001);
        aa.add(1002);
        List<Integer> bb = new ArrayList<>();
        bb.add(1001);
        bb.add(1002);
        Set<Integer> cc = new HashSet<>();
        Set<Integer> dd = new HashSet<>();
        dd.add(1);
        dd.add(2);
        //当 Collection 对象中不存在公共元素时返回真,否则返回假
       System.out.println( Collections.disjoint(aa,bb));//false
       System.out.println( Collections.disjoint(cc,dd));//true
    }

2、CollectionUtils.containsAny()

2.1、方法在org.apache.commons.collections.CollectionUtils中。

2.2、用于检查给定的 Collection 对象是否可能包含任何公共元素;存在公共元素时返回true,否则返回false。

public static boolean containsAny(Collection coll1, Collection coll2);

2.3、代码块

 public static boolean containsAny(Collection coll1, Collection coll2) {
        Iterator it;
        if (coll1.size() < coll2.size()) {
            it = coll1.iterator();

            while(it.hasNext()) {
                if (coll2.contains(it.next())) {
                    return true;
                }
            }
        } else {
            it = coll2.iterator();

            while(it.hasNext()) {
                if (coll1.contains(it.next())) {
                    return true;
                }
            }
        }

        return false;
    }

2.4、用法

    public static void main(String[] args) {
        List<Integer> aa = new ArrayList<>();
        aa.add(1001);
        aa.add(1002);
        List<Integer> bb = new ArrayList<>();
        bb.add(1001);
        bb.add(1002);
        Set<Integer> cc = new HashSet<>();
        Set<Integer> dd = new HashSet<>();
        dd.add(1);
        dd.add(2);
       System.out.println( CollectionUtils.containsAny(aa,bb));//true
       System.out.println( CollectionUtils.containsAny(cc,dd));//false
    }

3.retainAll(Collection<?> c)

3.1、方法在java.util 包中 。

3.2、根据返回的集合数判断;大于0时存在交集。

boolean retainAll(Collection<?> c);

3.3、代码块

 public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        return batchRemove(c, true);
    }

    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false;
        try {
            for (; r < size; r++)
                if (c.contains(elementData[r]) == complement)
                    elementData[w++] = elementData[r];
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r;
            }
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null;
                modCount += size - w;
                size = w;
                modified = true;
            }
        }
        return modified;
    }
   public boolean retainAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;
        Iterator<E> it = iterator();
        while (it.hasNext()) {
            if (!c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

3.4、用法

  public static void main(String[] args) {
        List<Integer> aa = new ArrayList<>();
        aa.add(1001);
        aa.add(1002);
        List<Integer> bb = new ArrayList<>();
        bb.add(1001);
        bb.add(1002);
        Set<Integer> cc = new HashSet<>();
        Set<Integer> dd = new HashSet<>();
        dd.add(1);
        dd.add(2);
        List<Integer> origin = new ArrayList<>();
        origin.addAll(aa);
        origin.retainAll(bb);
        System.out.println( origin.size() > 0 ? true : false);//true
        Set<Integer> origin1 = new HashSet<>();
        origin1.addAll(cc);
        origin1.retainAll(dd);
        System.out.println( origin1.size() > 0 ? true : false);//false

    }

二、jdk1.8以上

List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值