判空总结

76 阅读1分钟

List 是否为null

主要还是 stream 的使用

List<Integer> marketIds = sysUserService.getMarketIdsByUserId(userId); 
boolean isEmpty = marketIds.stream().allMatch(Objects::isNull); 
if (isEmpty) { 
    System.out.println("marketIds is effectively empty."); 
} else { 
    System.out.println("marketIds contains non-null elements."); 
}

使用 StringUtils 类(Apache Commons Lang)

如果您项目中已经引入了 Apache Commons Lang 库,那么可以使用 StringUtils 类中的静态方法 isNullOrEmpty() 或者 isBlank() 来进行更简洁的检查。这两个方法都可以处理 null 和空字符串的情况,而 isBlank() 还会进一步检查字符串是否只包含空白字符。

StringUtils 判空

StringUtils.isNotEmpty

StringUtils.isNotEmpty 是 Apache Commons Lang 库中的一个方法,用于检查字符串是否非空。非空的意思是字符串既不是 null 也不是空字符串。 代码示例:

import org.apache.commons.lang3.StringUtils;
 
public class Main {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "";
        String str3 = null;
 
        System.out.println(StringUtils.isNotEmpty(str1)); // 输出: true
        System.out.println(StringUtils.isNotEmpty(str2)); // 输出: false
        System.out.println(StringUtils.isNotEmpty(str3)); // 输出: false
    }
}

StringUtils.isNotBlank

它会在给定的字符串不是 null、不是空字符串且不只包含空白字符时返回 true

if (StringUtils.isNotBlank(personInfo.getFrontUrl())) {
     System.out.println("frontUrl has a valid value: " + personInfo.getFrontUrl());
} else {
     System.out.println("frontUrl is null, empty, or only contains whitespace.");
}

StringUtils.isBlank

        // 检查 frontUrl 是否为 null、空字符串或仅包含空白字符
        if (StringUtils.isBlank(lyPersonInfoWithUrlsVO.getFrontUrl())) {
            System.out.println("frontUrl is null, empty, or only contains whitespace");
        } else {
            System.out.println("frontUrl has a value");
        }

使用 == null 和 isEmpty()

这是最基本的方法,首先检查字符串是否为 null,然后使用 isEmpty() 方法检查字符串是否为空字符串。

if (lyPersonInfoWithUrlsVO.getFrontUrl() == null || lyPersonInfoWithUrlsVO.getFrontUrl().isEmpty()) { System.out.println("frontUrl is null or empty"); } else { System.out.println("frontUrl has a value"); }

使用 Objects.isNull() 和 Objects.nonNull()

从 Java 8 开始,java.util.Objects 类提供了 isNull()nonNull() 方法,可以用来简化对 null 的检查。

import java.util.Objects; 
if (Objects.isNull(lyPersonInfoWithUrlsVO.getFrontUrl()) || lyPersonInfoWithUrlsVO.getFrontUrl().isEmpty()) { System.out.println("frontUrl is null or empty"); } else { System.out.println("frontUrl has a value"); }