I am trying to simplify the following code.
The basic steps that the code should carry out are as follows:
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
Reference Variable value: Any reference variable in Java has a default value null.
Java 8 – Optional orElse() and orElseGet() methods These two methods orElse() and orElseGet() returns the value of Optional Object if it is no empty, if the object is empty then it returns the default value passed to this method as an argument.
Use Java 8 Optional
(no filter needed):
public static String orElse(String defaultValue) { return Optional.ofNullable(System.getProperty("property")).orElse(defaultValue); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With