CollectionUtils.isEmpty()作用:判断参数null或者其size等于0
CollectionUtils.isNotEmpty()作用:判断参数不为null且其size不等于0
添加依赖:
<dependencies>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
</dependencies>
演示判断集合是否为空和判断集合是否不为空的示例:
import org.apache.commons.collections.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List<Integer> listA = null;
List<Integer> listB = new ArrayList<>();
List<Integer> listC = new ArrayList<>();
listC.add(5);
listC.add(6);
// 判断集合是否为空
if (CollectionUtils.isEmpty(listA)) { // true
System.out.println("listA为空或size=0");
}
if (CollectionUtils.isEmpty(listB)) { // true
System.out.println("listB为空或size=0");
}
if (CollectionUtils.isEmpty(listC)) { // false
System.out.println("listC为空或size=0");
}
// 判断集合是否不为空
if (CollectionUtils.isNotEmpty(listA)) { // false
System.out.println("listA不为空且size不等于0");
}
if (CollectionUtils.isNotEmpty(listB)) { // false
System.out.println("listB不为空且size不等于0");
}
if (CollectionUtils.isNotEmpty(listC)) { // true
System.out.println("listC不为空且size不等于0");
}
}
}
运行结果:
![](https://img-blog.csdnimg.cn/img_convert/838afc9d589c4bc39433b57d4b0547aa.png)
演示两种isEmpty区别的示例:
import org.apache.commons.collections.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List<Integer> listA = null;
List<Integer> listB = new ArrayList<>();
List<Integer> listC = new ArrayList<>();
listC.add(5);
listC.add(6);
// public static boolean isEmpty(Collection coll) (org.apache.commons.collections.CollectionUtils)
// 和public boolean isEmpty()(java.util.ArrayList;)的区别
System.out.println(CollectionUtils.isEmpty(listA));
// System.out.println(listA.isEmpty()); // 打开该行注释程序会报错
System.out.println(CollectionUtils.isEmpty(listB));
System.out.println(listB.isEmpty());
System.out.println(CollectionUtils.isEmpty(listC));
System.out.println(listC.isEmpty());
}
}
运行结果:
![](https://img-blog.csdnimg.cn/img_convert/e5803dc33830413d9101ef6416aad873.png)