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 方法。

相关推荐
做运维的阿瑞1 小时前
Python原生数据结构深度解析:从入门到精通
开发语言·数据结构·后端·python·系统架构
璨sou1 小时前
Rust语言--基础入门到应用
后端·rust
一只学java的小汉堡2 小时前
Spring Boot 配置详解:从引导器到注解实战(初学者指南)
java·spring boot·后端
__XYZ2 小时前
Vala编程语言高级特性-弱引用和所有权
c语言·开发语言·后端·c#
IT_陈寒2 小时前
Python开发者必坑指南:3个看似聪明实则致命的‘优化’让我损失了50%性能
前端·人工智能·后端
Ivanqhz3 小时前
Rust的错误处理
开发语言·后端·rust
java1234_小锋5 小时前
[免费]基于Python的Flask+Vue进销存仓库管理系统【论文+源码+SQL脚本】
后端·python·flask
fly-phantomWing8 小时前
Maven的安装与配置的详细步骤
java·后端·maven·intellij-idea
学编程的小鬼11 小时前
SpringBoot 自动装配原理剖析
java·spring boot·后端
码事漫谈12 小时前
SIMD编程入门:让性能飞起来的实践指南
后端