Java-Check Not Null / Empty else asignar valor predeterminado
Estoy tratando de simplificar el siguiente código.
Los pasos básicos que el código debe llevar a cabo son los siguientes:
- Asignar a la cadena un valor predeterminado
- Ejecute un método
- Si el método devuelve una cadena null/empty, deje la cadena como predeterminada
- Si el método devuelve una cadena válida, establezca la cadena en este resultado
Un ejemplo sencillo sería:
String temp = System.getProperty("XYZ");
String result = "default";
if(temp != null && !temp.isEmpty()){
result = temp;
}
He hecho otro intento usando un ternario operador:
String temp;
String result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
El método isNotNullOrEmpty ()
private static boolean isNotNullOrEmpty(String str){
return (str != null && !str.isEmpty());
}
Es posible hacer todo esto en línea? Sé que podría hacer algo como esto:
String result = isNotNullOrEmpty(System.getProperty("XYZ")) ? System.getProperty("XYZ") : "default";
Pero estoy llamando al mismo método dos veces. Sería algo así como hacer algo como esto (que no funciona):
String result = isNotNullOrEmpty(String temp = System.getProperty("XYZ")) ? temp : "default";
Me gustaría inicializar la cadena 'temp' dentro de la misma línea. Es esto posible? ¿O qué debería estar haciendo?
Gracias por sus sugerencias.
Tim
4 answers
Sé que la pregunta es muy antigua, pero con genéricos se puede agregar un método más generalizado con funcionará para todos los tipos.
public static <T> T getValueOrDefault(T value, T defaultValue) {
return value == null ? defaultValue : value;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-21 17:04:29
Usar Java 8 Optional
(no se necesita filtro):
public static String orElse(String defaultValue) {
return Optional.ofNullable(System.getProperty("property")).orElse(defaultValue);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-21 17:05:00
Use org.apache.común.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);
Ambas de las opciones anteriores se imprimirán:
Predeterminado
Predeterminado
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-12 06:57:49
Parece que probablemente quieras un método simple como este:
public String getValueOrDefault(String value, String defaultValue) {
return isNotNullOrEmpty(value) ? value : defaultValue;
}
Entonces:
String result = getValueOrDefault(System.getProperty("XYZ"), "default");
En este punto, no necesitas temp
... ha utilizado efectivamente el parámetro method como una forma de inicializar la variable temporal.
Si realmente quieres temp
y no quieres un método extra, puedes hacerlo en una declaración, pero realmente no lo haría:
public class Test {
public static void main(String[] args) {
String temp, result = isNotNullOrEmpty(temp = System.getProperty("XYZ")) ? temp : "default";
System.out.println("result: " + result);
System.out.println("temp: " + temp);
}
private static boolean isNotNullOrEmpty(String str) {
return str != null && !str.isEmpty();
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-14 16:31:13