开发者

StringBuilder append() and null values

I have a list of Strings, 开发者_运维知识库and I want to concatenate them with spaces in between. So I'm using StringBuilder. Now if any of the Strings are null, they get stored in the StringBuilder literally as 'null'. Here is a small program to illustrate the issue:

public static void main(String ss[]) {
    StringBuilder sb = new StringBuilder();

    String s;
    s = null;

    System.out.println(sb.append("Value: ").append(s));
}

I'd expect the output to be "Value: " but it comes out as "Value: null"

Is there a way around this problem?


You can do a check on the object before appending it:

sb.append("Value: ");
if (s != null) sb.append(s);
System.out.println(sb);

A key point to make is that null is not the same an an empty String. An empty String is still a String object with associated methods and fields associated with it, where a null pointer is not an object at all.

From the documentation for StringBuilder's append method:

The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null, then the four characters "null" are appended.


I'm not sure why you'd expect it to come out empty, given that the documentation is pretty clear:

If str is null, then the four characters "null" are appended.

Basically you need to either not call append at all if you have a null reference, or switch the value for "".

You could write a method to do this substitution if you find yourself doing it a lot:

public static String nullToEmpty(String text) {
    return text == null ? "" : text;
}

Indeed, I've just looked at the Guava documentation and the Strings class has exactly that method (but with a parameter called string instead of text).


You can use commons-lang's StringUtils#defaultString():

sb.append("Value: ").append(StringUtils.defaultString(myVar));


With Java 8 you could also use the java.util.Optional class to provide a default value:

System.out.println(sb.append("Value: ").append(Optional.ofNullable(s).orElse("")));


In one line you can do:

System.out.println(sb.append("Value: ").append((s==null)?"":s));


import java.util.Objects;
...
sb.append(Objects.toString(s, ""));

Uses Java internal utils, no external libs are needed. toString takes String, checks if it is null and if it is null, then returns specified default value, in this case "" (empty string), if it is not null it returns provided string.


For my purpose, I needed to generalize Answer #2 a little bit. Here is the same function, taking Object as argument, instead of String:

private String nullToEmpty(Object obj) {
    return obj == null ? "" : obj.toString();
}


I combined the answer from geeksforgeeks.org and @Benas.

map = map.entrySet()
    .stream()
    .peek(entry -> entry.setValue(Objects.toString(entry.getValue(), "")))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Objects from java.utils.


Null check as @Shynthriir has mentioned is the simplest most efficient way (AFAIK) to get around the problem.

I would however strongly recommend initiating strings to an empty string String str = ""; instead, which would save you a lot of headache in a more complex programming effort.


You can do:

sb.Replace("= ,", "= null,");

or:

sb.append("Value: ").append((s != null)? s: "NULL");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜