Java各种数据类型判断是否为空或者为null方法

Java 各种数据类型判断是否为空或者为null方法

开发中经常对各种数据进行判断是否为空或者为null 对数据进行校验

最近开发中经常老是使用各种方式进行判断,这里就对常见的数据类型判断方法进行一个统计汇总,如果有错就请帮忙指出下。

对象类型 判断 Object org.apache.commons.lang3.ObjectUtils;

org.apache.commons.lang3.StringUtils;

Object o = new Object();

if (o !=null){
    
    
    System.out.println("not null");
}

//还可以使用
Object obj =null;
String s = ObjectUtils.toString(obj, "");
System.out.println(s+"1");
if (StringUtils.isBlank(s)){
    
    
    System.out.println("空");
}else {
    
    
    System.out.println("不为空");
}

List 判断 是否为空 这个包 org.springframework.util.CollectionUtils;

List<String> list = new ArrayList<>();
        boolean empty = CollectionUtils.isEmpty(list);
        if (empty) {
    
    
            System.out.println("空");
        }else {
    
    
            System.out.println("不为空");
        }

Map 判断 是否为空 org.springframework.util.CollectionUtils;

  HashMap<String, Object> map = new HashMap<>(16);
        if (CollectionUtils.isEmpty(map)){
    
    
            System.out.println("空");
        }else {
    
    
            System.out.println("不为空");
        }

String 判断 是否为空 org.apache.commons.lang3.StringUtils;

StringUtils 中有 俩个 方法 isNotEmpty 和 isNotBlank 基本是一样的

就是 isNotBlank 增加了空格\t \n \f \r 这些的判断忽略

String str = "str";
if (StringUtils.isNotEmpty(str)){
    
    

}
if (StringUtils.isNotBlank(str)){
    
    

}

基本类型 包装类型 都可以 使用以下

Integer都可以转化成String 然后判断

 Integer num =1;
if (StringUtils.isNotEmpty(String.valueOf(num))){
    
    
    System.out.println("不为空");
}

Long 都可以转化成String 然后判断

Long longNum =1L;
if (StringUtils.isNotEmpty(String.valueOf(longNum))){
    
    
    System.out.println("不为空");
}

猜你喜欢

转载自blog.csdn.net/weng74/article/details/114457292