CollectionUtils的使用

1、非空判断

判断集合是否为空

List<String>对象list,可以使用CollectionUtils中的isEmpty方法来判断list是否为空。代码如下

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

2、数组转换为List对象

使用CollectionUtils中的arrayToList方法将该数组转换为List<String>对象

复制代码
String[] array = {"a", "b", "c"};
List<String> list = CollectionUtils.arrayToList(array);
System.out.println(list);

3、枚举对象Enumeration转换成数组

使用CollectionUtils中的toArray方法将enumeration转换成String数组

复制代码
Enumeration<Object> enumeration = new StringTokenizer("shanghai", "hangzhou","shenzhen");

String[] array = (String[]) CollectionUtils.toArray(enumeration, new String[0]);

for (String s : array) {
    System.out.println(s);
}

4、数组合并到List对象

CollectionUtils中的mergeArrayIntoCollection方法将数组中的元素合并到List对象中

java 复制代码
String[] array = {"shanghai", "shenzhen", "hangzhou"};
List<String> list = new ArrayList<>();
CollectionUtils.mergeArrayIntoCollection(array, list);
System.out.println(list);

5、判断集合中是否包含指定元素

使用CollectionUtils中的contains方法来判断List对象中是否包含某个元素

java 复制代码
List<String> list = new ArrayList<>();
list.add("shanghai");
list.add("hangzhou");
boolean contains = CollectionUtils.contains(list.iterator(), "hangzhou");
System.out.println(contains);

6、判断集合A中是否包含集合B中的任意一个元素

使用CollectionUtils中的containsAny方法来判断

java 复制代码
    List<String> a = new ArrayList<>();
    a.add("shanghai");
    a.add("hangzhou");
    List<String> b = new ArrayList<>();
    b.add("shenzhen");
    b.add("hangzhou");
    boolean isContain = CollectionUtils.containsAny(a, b);
    System.out.println(isContain); 
相关推荐
子兮曰1 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
小羊没烦恼!1 天前
微服务化的基石——持续集成
java·大数据·word·powerpoint·.net
子兮曰1 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
俊昭喜喜里1 天前
java中的继承和多态的区别
java
小羊没烦恼!1 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
rockmelodies1 天前
# Windows Server2008 R2 Standard(SP1镜像U盘)重置本地管理员密码【完整详细步骤】
windows·密码破解
爱勇宝1 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
譕痕1 天前
JSONObject与JSONArray封装数据格式区别
java·json
胡写代码1 天前
别再前后端各写一套表单校验了
java·后端
小鱼能吃糖1 天前
缺陷修复总览 · mall电商项目:5类缺陷,1个病根,4个业务域
java·电商