CollectionUtils工具类

CollectionUtils工具类

这篇讲的CollectionUtils工具类是在apache下的,可以使代码更加简洁和安全。

使用前需导入依赖

<dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-collections4</artifactId>
        <version>4.3</version>
    </dependency>

API常用方法

        /**
         * 1、除非元素为null,否则向集合添加元素
         */
        CollectionUtils.addIgnoreNull(personList,null);
        /**
         * 2、将两个已排序的集合a和b合并为一个已排序的列表,以便保留元素的自然顺序
         */
        CollectionUtils.collate(Iterable<? extends O> a, Iterable<? extends O> b)
        /**
         * 3、将两个已排序的集合a和b合并到一个已排序的列表中,以便保留根据Comparator c的元素顺序。
         */
        CollectionUtils.collate(Iterable<? extends O> a, Iterable<? extends O> b, Comparator<? super O> c)
        /**
         * 4、返回该个集合中是否含有至少有一个元素
         */
        CollectionUtils.containsAny(Collection<?> coll1, T... coll2)
        /**
         * 5、如果参数是null,则返回不可变的空集合,否则返回参数本身。(很实用 ,最终返回List EMPTY_LIST = new EmptyList<>())
         */
        CollectionUtils.emptyIfNull(Collection<T> collection)
        /**
         * 6、空安全检查指定的集合是否为空
         */
        CollectionUtils.isEmpty(Collection<?> coll)
        /**
         * 7、 空安全检查指定的集合是否为空。
         */
        CollectionUtils.isNotEmpty(Collection<?> coll)
        /**
         * 8、反转给定数组的顺序。
         */
        CollectionUtils.reverseArray(Object[] array);
        /**
         * 9、差集
         */
        CollectionUtils.subtract(Iterable<? extends O> a, Iterable<? extends O> b)
        /**
         * 10、并集
         */
        CollectionUtils.union(Iterable<? extends O> a, Iterable<? extends O> b)
        /**
         * 11、交集
         */
        CollectionUtils.intersection(Collection a, Collection b)
        /**
         *12、 交集的补集(析取)
         */
        CollectionUtils.disjunction(Collection a, Collection b)
原文地址:https://www.cnblogs.com/niudaben/p/12366508.html