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

des*_*nuj 6 java null java-stream

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

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 字段是否是一个好方法?

Vad*_*zim 10

使用 Guava 的emptyToNull 的另一种选择:

text = Strings.emptyToNull(text);
Run Code Online (Sandbox Code Playgroud)


Mik*_*keM 3

在您的示例中,如果 text 为 null,则 text.equals(null) 将导致 NPE。你会想要这样的东西:

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

如果您希望空格也被视为空,则需要在调用 isEmpty() 之前调用 trim():

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

由于您想重用此代码,因此将其设为可以从任何类调用的实用程序方法是有意义的:

public static String setNullOnEmpty(final String text) {
    return text != null && text.trim().isEmpty() ? null : text;
}
Run Code Online (Sandbox Code Playgroud)