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

相关推荐
Victor3566 分钟前
Redis(125)Redis在社交网络中的应用有哪些?
后端
Victor3568 分钟前
Redis(124)Redis在电商系统中的应用有哪些?
后端
武子康10 分钟前
Java-173 Neo4j + Spring Boot 实战:从 Driver 到 Repository 的整合与踩坑
java·数据库·spring boot·后端·spring·nosql·neo4j
凌波粒11 分钟前
SpringMVC基础教程(2)--Controller/RestFul风格/JSON/数据转发和重定向
java·后端·spring·json·restful
程序员爱钓鱼1 小时前
Python 编程实战 · 实用工具与库 — Flask 路由与模板
前端·后端·python
程序员爱钓鱼1 小时前
Python 编程实战 · 实用工具与库 — Django 项目结构简介
后端·python·面试
小王不爱笑1329 小时前
Spring AOP(AOP+JDBC 模板 + 转账案例)
java·后端·spring
Python私教10 小时前
Rust基本语法
后端
Python私教10 小时前
Rust环境搭建
后端
jakeswang10 小时前
ServletLess架构简介
java·后端·servletless