Get empty string when null

后端 未结 7 735
予麋鹿
予麋鹿 2020-12-07 19:55

I want to get string values of my fields (they can be type of long string or any object),

if a field is null then it should return empty string, I did this with guav

相关标签:
7条回答
  • 2020-12-07 20:17

    Use an inline null check

    gearBox == null ? "" : String.valueOf(gearBox);
    
    0 讨论(0)
  • 2020-12-07 20:17

    Since you're using guava:

    Objects.firstNonNull(gearBox, "").toString();
    
    0 讨论(0)
  • 2020-12-07 20:25

    If you don't mind using Apache commons, they have a StringUtils.defaultString(String str) that does this.

    Returns either the passed in String, or if the String is null, an empty String ("").

    If you also want to get rid of "null", you can do:

    StringUtils.defaultString(str).replaceAll("^null$", "")
    

    or to ignore case:

    StringUtils.defaultString(str).replaceAll("^(?i)null$", "")
    
    0 讨论(0)
  • 2020-12-07 20:29

    If alternative way, Guava provides Strings.nullToEmpty(String).

    Source code

    String str = null;
    str = Strings.nullToEmpty(str);
    System.out.println("String length : " + str.length());
    

    Result

    0
    
    0 讨论(0)
  • 2020-12-07 20:31

    In Java 9+ use : Objects.requireNonNullElse (obj, defaultObj) https://docs.oracle.com/javase/9/docs/api/java/util/Objects.html#requireNonNullElse-T-T-

    //-- returns empty string if obj is null
    Objects.requireNonNullElse (obj, "")   
    
    0 讨论(0)
  • 2020-12-07 20:40

    You can use Objects.toString() (standard in Java 7):

    Objects.toString(gearBox, "")
    
    Objects.toString(id, "")
    

    From the linked documentation:

    public static String toString(Object o, String nullDefault)

    Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.

    Parameters:
    o - an object
    nullDefault - string to return if the first argument is null

    Returns:
    the result of calling toString on the first argument if it is not null and the second argument otherwise.

    See Also:
    toString(Object)

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