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);
相关推荐
Wang15305 小时前
jdk内存配置优化
java·计算机网络
0和1的舞者5 小时前
Spring AOP详解(一)
java·开发语言·前端·spring·aop·面向切面
Wang15305 小时前
Java多线程死锁排查
java·计算机网络
小小星球之旅6 小时前
CompletableFuture学习
java·开发语言·学习
利刃大大6 小时前
【SpringBoot】Spring事务 && @Transactional详解 && Spring事务失效问题
spring boot·spring·事务
jiayong236 小时前
知识库概念与核心价值01
java·人工智能·spring·知识库
皮皮林5517 小时前
告别 OOM:EasyExcel 百万数据导出最佳实践(附开箱即用增强工具类)
java
Da Da 泓7 小时前
多线程(七)【线程池】
java·开发语言·线程池·多线程
To Be Clean Coder7 小时前
【Spring源码】getBean源码实战(三)
java·mysql·spring
Wokoo78 小时前
开发者AI大模型学习与接入指南
java·人工智能·学习·架构