Java - Check Not Null/Empty else assign default value
Solution 1
I know the question is really old, but with generics one can add a more generalized method with will work for all types.
public static <T> T getValueOrDefault(T value, T defaultValue) {
return value == null ? defaultValue : value;
}
Solution 2
Use Java 8 Optional
(no filter needed):
public static String orElse(String defaultValue) {
return Optional.ofNullable(System.getProperty("property")).orElse(defaultValue);
}
Solution 3
If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)
Solution 4
Use org.apache.commons.lang3.StringUtils
String emptyString = new String();
result = StringUtils.defaultIfEmpty(emptyString, "default");
System.out.println(result);
String nullString = null;
result = StringUtils.defaultIfEmpty(nullString, "default");
System.out.println(result);
Both of the above options will print:
default
default
Solution 5
You can use this method in the ObjectUtils
class from org.apache.commons.lang3 library :
public static <T> T defaultIfNull(T object, T defaultValue)
Related videos on Youtube
Cam1989
Updated on March 31, 2022Comments
-
Cam1989 about 2 years
I am trying to simplify the following code.
The basic steps that the code should carry out are as follows:
- Assign String a default value
- Run a method
- If the method returns a null/empty string leave the String as default
- If the method returns a valid string set the String to this result
A Simple example would be:
String temp = System.getProperty("XYZ"); String result = "default"; if(temp != null && !temp.isEmpty()){ result = temp; }
I have made another attemp using a ternary operator:
String temp; String result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
The isNotNullOrEmpty() Method
private static boolean isNotNullOrEmpty(String str){ return (str != null && !str.isEmpty()); }
Is it possible to do all of this in-line? I know I could do something like this:
String result = isNotNullOrEmpty(System.getProperty("XYZ")) ? System.getProperty("XYZ") : "default";
But I am calling the same method twice. I would be something like to do something like this (which doesn't work):
String result = isNotNullOrEmpty(String temp = System.getProperty("XYZ")) ? temp : "default";
I would like to initialize the 'temp' String within the same line. Is this possible? Or what should I be doing?
Thank you for your suggestions.
Tim
-
Holger almost 3 years
System.getProperty("XYZ", "default")
-
hagrawal almost 9 years@fge Lets say it is not case of System.getProperty() but some method which doesn't have this extra parameter for default value. Then trick will work, it is scalable.
-
Cam1989 almost 9 yearsHow did I make this so complicated!? Thank you very much! I have used the getValueOrDefault() method. Great answer.
-
Q8i almost 8 yearsWOW! Compared to swift's
s = q ?? r
. -
Cam1989 almost 7 yearsThanks shibashis. I still use this code and have a method for lots of object types! I will try with generics instead to simplify the code. Thank you
-
Jon Skeet almost 7 years@Cam1989: This doesn't answer the question you asked though, because it doesn't handle empty strings... it only deals with the value being
null
, not empty... if that's what you wanted, that's what you should have asked. This is a perfectly good solution to a different problem, but it is a solution to a different problem... -
Steve Goossens over 6 yearsit would meet the empty requirement by replacing "value == null" with "isNotNullOrEmpty(value)" and switching value and defaultValue in the ternary responses
-
Ryan Burbidge almost 5 yearsOptionals should not be created for flow control within a method. This is called out as an anti-pattern by the developers who built Optional. youtube.com/watch?amp=&v=Ej0sss6cq14
-
PAX over 4 years@RyanBurbidge, and the reason: You unnecessarily create an object in your simple method (Optional object).
-
jmm almost 4 yearsThis checks for
null
, but not for empty Strings. It's better to useStringUtils.defaultIfBlank
instead -
brunch875 over 3 yearsCareful! While the ternary operator itself is lazy, this solution isn't! Which means a call to
myThing = getValueOrDefault(thing, new Thing());
will create and discard thatnew Thing()
ifthing
is not null. You may want to adapt this function to take a lambda instead so you may dogetValueOrDefault(thing, Thing::new)
instead. -
brunch875 over 3 years@PAX, if that's the only reason you can avoid it by using
Optional::orElseGet
instead. I personally prefer the ternary operator since it's just as lazy and shorter. -
Pavel about 3 years@RyanBurbidge, nice reference, thanks! Relevant part of the video: 27:44 - 30:00
-
kap about 3 yearsGreat method, finally we got it. It's a shame it does not do automatic
int
tolong
casting. -
Holger almost 3 years@Q8i of course, if you make an operation unnecessarily complicated, you want to max it out. As otherwise, you could simply use
System.getProperty("property", defaultValue)
that does the job without additional syntactic constructs. -
Holger almost 3 years@brunch875 Since Java 9, this functionality exist as standard API method:
Objects.requireNonNullElse(T obj, T defaultObj)
, including a variant with lazy construction of the fallback,Objects.requireNonNullElseGet(T obj, Supplier<? extends T> supplier)
. -
rendon over 2 yearsI don't know why this solution is so popular, it's quite verbose.
-
Pierre C about 2 yearsThere is also
StringUtils.defaultIfBlank
to provide a default if the string is null or blank (e.g. contains spaces only) :result = StringUtils.defaultIfBlank(emptyString, "default");
.