You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中含null/空值的字符串比较:null与空串判定为相等

Java中兼容null/空串的字符串比较方法

需要实现的核心逻辑:所有null与空串("")的组合都判定为相等,具体符合以下场景:

onetwo比较结果
""""true
""nulltrue
null""true
nullnulltrue

给你两种可行的实现方式:

1. 自定义工具方法

自己写个静态方法就能搞定,逻辑是把null统一转换成空串,再做常规比较:

public static boolean equalsNullOrEmpty(String str1, String str2) {
    // 将null转为空串,空串保持不变
    String processedStr1 = str1 == null ? "" : str1;
    String processedStr2 = str2 == null ? "" : str2;
    // 执行字符串相等比较
    return processedStr1.equals(processedStr2);
}

如果需要忽略大小写,把equals换成equalsIgnoreCase就行。

2. 用Apache Commons Lang库实现

如果项目里已经引入了Apache Commons Lang 3.x,直接借助工具类简化代码:

import org.apache.commons.lang3.StringUtils;

public static boolean equalsNullOrEmpty(String str1, String str2) {
    // defaultString会把null转为空串,空串原样返回
    return StringUtils.defaultString(str1).equals(StringUtils.defaultString(str2));
}

同样,要忽略大小写的话,替换成equalsIgnoreCase即可。

内容的提问来源于stack exchange,提问作者Johnny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 20:07:42