Reputation: 11835
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 guava;
nullToEmpty(String.valueOf(gearBox))
nullToEmpty(String.valueOf(id))
...
But this returns null if gearbox is null! Not empty string because valueOf methdod returns string "null" which leads to errors.
Any Ideas?
EDIt: there are 100s fields I look for something easy to implement
Upvotes: 119
Views: 202602
Reputation: 178
StringUtils.defaultString(String str)
Returns either the passed in String, or if the String is null, an empty String ("").
Example from java doc
StringUtils.defaultString(null)
will return""
StringUtils.defaultString("")
will return""
StringUtils.defaultString("bat")
will return"bat"
Upvotes: 14
Reputation: 1306
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, "")
Upvotes: 6
Reputation: 431
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
Upvotes: 25
Reputation: 31035
For java 8 you can use Optional approach:
Optional.ofNullable(gearBox).orElse("");
Optional.ofNullable(id).orElse("");
Upvotes: 71
Reputation: 1230
Since you're using guava:
Objects.firstNonNull(gearBox, "").toString();
Upvotes: 6
Reputation: 46219
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$", "")
Upvotes: 38
Reputation: 129517
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 isnull
Returns:
the result of callingtoString
on the first argument if it is notnull
and the second argument otherwise.See Also:
toString(Object)
Upvotes: 258
Reputation: 1765
Use an inline null check
gearBox == null ? "" : String.valueOf(gearBox);
Upvotes: 10