判空方法分享
下文笔者讲述java中对字符串,list, Map是否为空的判断方法分享,如下所示
1.引入commons-lang3,jar包 2.使用其中的方法,即可对这些对象进行非空判断例:
一、字符串pank
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version> <!-- 替换为最新版本号 -->
</dependency>
import org.apache.commons.lang3.StringUtils;
public class Main {
public static void main(String[] args) {
String myString = "Hello, World!";
// 判断字符串是否为空
if (StringUtils.isEmpty(myString)) {
System.out.println("字符串为空");
} else {
System.out.println("字符串不为空");
}
// 判断字符串是否为空或只包含空格
if (StringUtils.isBlank(myString)) {
System.out.println("字符串为空或只包含空格");
} else {
System.out.println("字符串不为空且不只包含空格");
}
}
}
二、List判空
import org.apache.commons.collections
// List判空
List<String> myList = new ArrayList<>();
if (CollectionUtils.isEmpty(myList)) {
System.out.println("List为空");
} else {
System.out.println("List不为空");
}
三、Map
import org.apache.commons.collections.MapUtils
// Map判空
Map<String, Integer> myMap = new HashMap<>();
if (MapUtils.isEmpty(myMap)) {
System.out.println("Map为空");
} else {
System.out.println("Map不为空");
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


