Java【代码 12】判断一个集合是否包含另一个集合中的一个或多个元素 retainAll() 及其他方法

1.原因说明

业务中有这么一个逻辑:判断第一个集合里包含第二个集合中的一个或多个元素。首先想到的是 contains() 但是它的参数只能传 Object,还有另一个也就是 retainAll() 它可以传 Collection<?>

2.代码测试

bash 复制代码
public class TestRetainAll {
    public static void main(String[] args) {

        // 创建一个集合
        ArrayList<String> one = new ArrayList<>();
        one.add("a");
        one.add("b");
        one.add("c");
        System.out.println("ArrayList 1: " + one);

        // 创建另一个集合
        ArrayList<String> other = new ArrayList<>();
        other.add("a");
        other.add("b");
        other.add("d");
        System.out.println("ArrayList 2: " + other);

        // 前者是否包含后者某个元素
        boolean isContains = isContainsOne(one, other);
        System.out.println("ArrayList 1: " + one + " ; isContains:" + isContains);

        // 使用retainAll运算后
        boolean isRetainAll = one.retainAll(other);
        System.out.println("ArrayList 1: " + one + " ; isRetainAll:" + isRetainAll);
    }

    /**
     * 前者是否包含后者某个元素
     *
     * @param oneList   第一个集合
     * @param otherList 第二个集合
     * @return 是否包含
     */
    private static boolean isContainsOne(ArrayList<String> oneList, ArrayList<String> otherList) {
        for (String one : otherList) {
            boolean contains = oneList.contains(one);
            if (contains) {
                return true;
            }
        }
        return false;
    }
}

运行结果:

bash 复制代码
ArrayList 1: [a, b, c]
ArrayList 2: [a, b, d]
ArrayList 1: [a, b, c] ; isContains:true
ArrayList 1: [a, b] ; isRetainAll:true

3.总结

retainAll 方法:

Retains only the elements in this list that are contained in the specified collection. In other words, removes from this list all of its elements that are not contained in the specified collection.

只保留此列表中包含在指定集合中的元素。换句话说,从该列表中删除指定集合中不包含的所有元素。我看一下源码:

bash 复制代码
	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;
    }

实际上就是求交集,但是交集的结果放在了第一个集合里,如果后续还要使用第一个集合就会有影响,而且 retainAll 的返回值说明的是 是否删除了元素 我们可以看下边的两个例子:

bash 复制代码
ArrayList 1: [a, b, c]
ArrayList 2: [e, f, g]
ArrayList 1: [a, b, c] ; isContains:false
ArrayList 1: [] ; isRetainAll:true

ArrayList 1: [a, b, c]
ArrayList 2: [a, b, c]
ArrayList 1: [a, b, c] ; isContains:true
ArrayList 1: [a, b, c] ; isRetainAll:false

由此看来 retainAll 的返回值是无法满足 判断一个集合是否包含另一个集合中的一个或多个元素 这个逻辑的,原因是:

  • 全部包含返回值为false
  • 部分包含返回值为true
  • 不包含返回值也是true

所有只能使用 isContainsOne 方法。

相关推荐
魔尔助理顾问3 小时前
系统整理Python的循环语句和常用方法
开发语言·后端·python
程序视点3 小时前
Java BigDecimal详解:小数精确计算、使用方法与常见问题解决方案
java·后端
你的人类朋友3 小时前
❤️‍🔥微服务的拆分策略
后端·微服务·架构
AI小智5 小时前
后端变全栈,终于可以给大家推出我的LangChain学习小站了!
后端
lkf197115 小时前
商品中心—1.B端建品和C端缓存
开发语言·后端·缓存
我的ID配享太庙呀6 小时前
Django 科普介绍:从入门到了解其核心魅力
数据库·后端·python·mysql·django·sqlite
java叶新东老师6 小时前
goland编写go语言导入自定义包出现: package xxx is not in GOROOT (/xxx/xxx) 的解决方案
开发语言·后端·golang
码事漫谈8 小时前
C++模板元编程从入门到精通
后端
_風箏8 小时前
Java【代码 14】一个用于判断磁盘空间和分区表是否需要清理的工具类
后端
_風箏8 小时前
Java【代码 13】前端动态添加一条记后端使用JDK1.8实现map对象根据key的部分值进行分组(将map对象封装成指定entity对象)
后端