小编des*_*nuj的帖子

如果 String 为空,如何设置 null 值?

有时开发人员会检查字符串是否为值,如果是,则将这些字符串设置为空值:

if (text == null) {
    text = "";
}
Run Code Online (Sandbox Code Playgroud)

我想做的是写相反的if语句:

if (text.isEmpty()) {
    text = null;
}
Run Code Online (Sandbox Code Playgroud)

但是...首先 - 我必须(像往常一样)检查这个 String 是否为 null 以避免 NullPointerException,所以现在它看起来像这样(非常难看,但是 KISS):

if (!text == null) {
    if (text.isEmpty()) {
        text = null;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的类有几个字符串字段,我必须为所有这些字段准备这个解决方案。对于更高效的代码有什么基本想法吗?将其延伸为 lambda 表达式并迭代此类中的所有 String 字段是否是一个好方法?

java null java-stream

6
推荐指数
2
解决办法
2万
查看次数

标签 统计

java ×1

java-stream ×1

null ×1