Java set values after if else loop in one line

Viewed 1209

How do I achieve setting the value inside if else in one line?

String amount = myJSON.optString("cValue")
double cValue = (amount != null && !amount.isEmpty()) ? Double.parseDouble(amount) : 0;
if (cValue > 0) {
    mySavings.setCouponValue(cValue);
} else {
    mySavings.setCouponValue(0.0);
}
5 Answers

You could simply do :

mySavings.setCouponValue((cValue > 0 ? cValue : 0.0));

You can code like this:

mySavings.setCouponValue((cValue > 0 ? cValue : 0.0));

Further you can use assert in your method to avoid if else.

You could simply use a ternary operator to set the value, without having to create a temporary variable "cValue", just for comparison

String amount = myJSON.optString("cValue")
mySavings.setCouponValue((amount != null && !amount.isEmpty()) ? Double.parseDouble(amount) : 0.0);

as an alternative if you're using Java 8 or above, you can do like this :

mySavings.setCouponValue(Optional.ofNullable(amount).map(cValue -> !cValue.isEmpty() ?  Double.parseDouble(cValue):0).orElse(0.0));

For completeness

mySavings.setCouponValue(Math.max(0.0, cValue));

Useful if you were really committed to writing terrifying "one liners". In this case by avoiding introducing the cValue variable.

Related