Java开发中常用CollectionUtils方式,以及Spring中CollectionUtils常用方法示例

场景

Java开发中常用的CollectionUtils

一、Spring Framework的CollectionUtils

包路径:org.springframework.util.CollectionUtils

核心方法:

isEmpty(Collection<?> coll)

复制代码
List<String> list = null;
boolean empty = CollectionUtils.isEmpty(list);  // true

containsAny(Collection<?> source, Collection<?> candidates)

复制代码
boolean hasCommon = CollectionUtils.containsAny(List.of(1,2),  Set.of(2,3));  // true

二、Apache Commons Collections的CollectionUtils

包路径:org.apache.commons.collections4.CollectionUtils

特色方法:

isEqualCollection(Collection<?> a, Collection<?> b)

复制代码
boolean equal = CollectionUtils.isEqualCollection(
    List.of("A",  "B", "B"),
    List.of("B",  "A", "B")
); // true(忽略顺序)

collate(Iterable<? extends T> a, Iterable<? extends T> b, Comparator<? super T> c)

复制代码
List<Integer> merged = CollectionUtils.collate(
    List.of(1,  3),
    List.of(2,  4),
    Comparator.naturalOrder()
); // [1,2,3,4]

三、Google Guava的Collections2

包路径:com.google.common.collect.Collections2

高阶用法:

filter(Collection<E>, Predicate<? super E>)

复制代码
Collection<String> filtered = Collections2.filter(
    Lists.newArrayList("a",  "b", null),
    Objects::nonNull
); // ["a", "b"]

transform(Collection<F>, Function<? super F, ? extends T>)

复制代码
Collection<Integer> lengths = Collections2.transform(
    List.of("aa",  "bbb"),
    String::length
); // [2, 3]

Java工具库Guava的集合工具类Iterables、Lists、Sets、Maps、Multisets、Multimaps的常用方法示例:

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/127926429

四、Hutool的CollUtil

包路径:cn.hutool.core.collection.CollUtil

国产工具亮点:

newArrayList(E... elements)

复制代码
List<String> list = CollUtil.newArrayList("a",  "b"); // 可变列表

groupByField(Collection<T>, String fieldName)

复制代码
List<User> users = Arrays.asList(new  User(1), new User(2));
Map<Integer, List<User>> group = CollUtil.groupByField(users,  "id");

五、Java标准库的Collections

基础工具类:

synchronizedCollection(Collection<T> c)

复制代码
Collection<String> syncColl = Collections.synchronizedCollection(new  ArrayList<>());

unmodifiableCollection(Collection<? extends T> c)

复制代码
Collection<Integer> immutable = Collections.unmodifiableCollection(List.of(1,2));

工具类对比选择指南

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi

实现

Spring Framework中CollectionUtils工具类的核心方法解析及使用示例

一、集合判空操作

复制代码
        List<String> list = new ArrayList<>();
        boolean empty = CollectionUtils.isEmpty(list); 
        System.out.println(empty);

        Map<String, Object> map = Collections.singletonMap("key",  "value");
        boolean notEmpty = CollectionUtils.isEmpty(map); 
        System.out.println(notEmpty);

二、集合合并与转换

mergeArrayIntoCollection()

复制代码
        String[] arr = {"a", "b"};
        List<String> target = new ArrayList<>(List.of("c"));
        CollectionUtils.mergeArrayIntoCollection(arr,  target);
        System.out.println(target);

toIterator()

复制代码
        Vector<String> vector = new Vector<>(Set.of("x",  "y"));
        Enumeration<String> en = vector.elements();
        Iterator<String> it = CollectionUtils.toIterator(en);
        while (it.hasNext()){
            System.out.println(it.next());
        }

三、条件过滤与查找

findFirstMatch()

复制代码
        List<Integer> source = List.of(1,  2, 3);
        List<Integer> candidates = List.of(3,  4);
        Integer match = CollectionUtils.findFirstMatch(source,  candidates); // 3
        System.out.println(match);

containsAny()

复制代码
        boolean hasCommon = CollectionUtils.containsAny(
                List.of("A",  "B"),
                Set.of("B",  "C")
        ); // true
        System.out.println(hasCommon);

        boolean hasCommon1 = CollectionUtils.containsAny(
                List.of("A",  "B"),
                Set.of("D",  "C")
        ); // false
        System.out.println(hasCommon1);

四、特殊集合操作

hasUniqueObject()

复制代码
        List<Object> singleton = Collections.singletonList("unique");
        boolean isUnique = CollectionUtils.hasUniqueObject(singleton);  // true
        System.out.println(isUnique);

toMultiValueMap()

复制代码
        //将一个键值对的集合转换成一个 MultiValueMap,其中每个键可以映射到多个值。这对于处理例如表单提交数据、查询参数等场景特别有用。
        List<Pair<String, Integer>> pairs = List.of(
                Pair.of("a",  1),
                Pair.of("a",  2)
        );

        Map<String, List<Integer>> tempMap = new HashMap<>();
        pairs.forEach(pair  ->
                tempMap.computeIfAbsent(pair.getKey(),  k -> new ArrayList<>())
                        .add(pair.getValue())
        );

        MultiValueMap<String, Integer> map1 = CollectionUtils.toMultiValueMap(tempMap);
        System.out.println(map1);
相关推荐
没有bug.的程序员15 小时前
Java锁优化:从synchronized到CAS的演进与实战选择
java·开发语言·多线程·并发·cas·synchronized·
麦兜*15 小时前
SpringBoot Profile多环境配置详解,一套配置应对所有场景
java·数据库·spring boot
MetaverseMan15 小时前
rpc节点: synchronized (this) + 双检锁,在 race condition 的情况下分析
java·区块链
笃行客从不躺平15 小时前
Seata + AT 模式 复习记录
java·分布式
CTO Plus技术服务中15 小时前
强悍的Go语言开发面试题和答案
java·面试·职场和发展
黎雁·泠崖15 小时前
Java static入门:概述+静态变量特点与基础实战
java·开发语言
努力也学不会java15 小时前
【Spring Cloud】 服务注册/服务发现
人工智能·后端·算法·spring·spring cloud·容器·服务发现
一条大祥脚15 小时前
26.1.21 根号分治 相向双指针
java·开发语言·redis
迦蓝叶15 小时前
JDBC元数据深度实战:企业级数据资源目录系统构建指南
java·jdbc·企业级·数据资源·数据血缘·数据元管理·构建指南