Java - Check Not Null/Empty else assign default value
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
Use Java 8 Optional
(no filter needed):
public static String orElse(String defaultValue) {
return Optional.ofNullable(System.getProperty("property")).orElse(defaultValue);
}
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;
}
If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)
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