StringBuilder append() and null values

后端 未结 8 923
借酒劲吻你
借酒劲吻你 2021-02-06 21:54

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 ar

相关标签:
8条回答
  • 2021-02-06 22:31

    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("")));

    0 讨论(0)
  • 2021-02-06 22:33

    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.

    0 讨论(0)
  • 2021-02-06 22:35

    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();
    }
    
    0 讨论(0)
  • 2021-02-06 22:36
    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.

    0 讨论(0)
  • 2021-02-06 22:38

    In one line you can do:

    System.out.println(sb.append("Value: ").append((s==null)?"":s));
    
    0 讨论(0)
  • 2021-02-06 22:45

    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).

    0 讨论(0)
提交回复
热议问题