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]
相关推荐
五岳5 小时前
分库分表数据源ShardingSphereDataSource的Connection元数据误用问题分析
java·mysql·爬坑
带刺的坐椅5 小时前
迈向 MCP 集群化:Solon AI (支持 Java8+)在解决 MCP 服务可扩展性上的探索与实践
java·ai·llm·solon·mcp
鼠爷ねずみ6 小时前
SpringCloud前后端整体开发流程-以及技术总结文章实时更新中
java·数据库·后端·spring·spring cloud
代码or搬砖6 小时前
String字符串
android·java·开发语言
AM越.8 小时前
Java设计模式详解--装饰器设计模式(含uml图)
java·设计模式·uml
5980354158 小时前
【java工具类】小数、整数转中文大写
android·java·开发语言
JIngJaneIL8 小时前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
吃喝不愁霸王餐APP开发者8 小时前
Java后端服务在对接全国性霸王餐API时的多数据中心部署与就近调用策略
java·开发语言
从心归零8 小时前
springboot-jpa的批量更新方法
java·spring boot·spring