I want to replace two ternary operator by a java 8 optional expression
Here is the two ternary operator:
valueA and valueB are string
valueA != null ? valueA.length() < 3 ? "0"+valueA : valueA : valueB
how to do it ?
I want to replace two ternary operator by a java 8 optional expression
Here is the two ternary operator:
valueA and valueB are string
valueA != null ? valueA.length() < 3 ? "0"+valueA : valueA : valueB
how to do it ?
Try this.
String result = Optional.ofNullable(valueA)
.map(s -> s.length() < 3 ? "0" + s : s)
.orElse(valueB);
The Optional
class wraps a null or an object. Using Optional
does not eliminate the nulls, nor can it replace your ternary tests. However, an Optional
may simplify your ternaries: see Answer by saka1029.
You could simply call Optional.ofNullable
and pass the result of your nested ternary tests.
Optional < String > optional =
Optional.ofNullable(
valueA != null ? valueA.length() < 3 ? "0" + valueA : valueA : valueB
)
;
(Replace String
with your particular data type in code above.)
As I read your ternaries, any of five outcomes are possible:
valueA
is null)valueA
valueA
valueB
having an objectvalueB
being nullOur call to Optional.ofNullable
handles all five.
Optional
is returned.Optional
containing an object is returned.As Lino commented, the original purpose to the Optional
class was for use as the return type of a method, to signal when null is a legitimate value rather a problem (error, unknown, etc.). While you are free to use Optional
in other ways, doing so is likely to be a poor choice.