commons-collections4工具常用方法

commons-collections4是Apache Commons项目中的一个模块,提供了一系列处理集合和映射的工具类、接口和算法。它是在commons-collections的基础上进行了改进和增强,为Java开发者提供了更多集合操作的功能和便利性。

引入依赖

复制代码
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.4</version>
        </dependency>

判断集合是否为null或长度为0

java 复制代码
        List<String> a = new ArrayList<>();
        System.out.println(CollectionUtils.isEmpty(a)); // true
        a=null;
        System.out.println(CollectionUtils.isEmpty(a)); // true

取集合的交集

java 复制代码
        List<String> a = new ArrayList<>();
        a.add("a");
        a.add("b");
        a.add("c");
        List<String> b = new ArrayList<>();
        b.add("c");
        b.add("1");
        b.add("2");
        System.out.println(CollectionUtils.intersection(a, b)); // [c]

取集合并集

java 复制代码
        List<String> a = new ArrayList<>();
        a.add("a");
        a.add("b");
        a.add("c");
        List<String> b = new ArrayList<>();
        b.add("c");
        b.add("1");
        b.add("2");
        System.out.println(CollectionUtils.union(a,b)); // [a, 1, b, 2, c]

取集合差集

java 复制代码
       List<String> a = new ArrayList<>();
        a.add("a");
        a.add("b");
        a.add("c");
        List<String> b = new ArrayList<>();
        b.add("c");
        b.add("1");
        b.add("2");
        // a-b的值
        System.out.println(CollectionUtils.subtract(a,b)); // [a, b]
相关推荐
嘿嘿-661 小时前
Windows 一键使用 GPT-6 Astra:Codex CLI 配置教程
java·人工智能·windows·gpt·chatgpt·web
策案案案2 小时前
YOLO: 将AI Agents嵌入到IntelliJ IDEA
java·大数据·人工智能·笔记·yolo·microsoft·intellij-idea
辰烨chenye3 小时前
LeetCode Hot 100 题解 · 堆篇
java·算法·leetcode
shehuiyuelaiyuehao4 小时前
算法29,前缀和,除自身以外的数组的乘积
java·数据结构·算法
小刘在重生~4 小时前
Java常用类|String类详解 + BigDecimal精准计算(含面试题)
java·开发语言·python
随遇而安zx4 小时前
【多线程】---JMM 与 volatile 深度解析
java·多线程
邪修king5 小时前
Re:Linux系统篇(十九):进程篇(八): 进程等待详解:wait/waitpid,僵尸进程到底该如何回收
java·开发语言
啵啵啵鱼5 小时前
DS-顺序表
java·数据结构·笔记·后端·链表·obsidian
TinyMemory5 小时前
Java 面向对象核心入门(七):方法重载 Overload,同一个方法名能干不一样的活
java·面向对象·overload·方法重载