-3

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 ?

flamant
  • 733
  • 4
  • 15
  • 41
  • 2
    First change the inner ternary as an optional and then the outer. Maybe perhaps it would be a good idea for readability to split them to different lines also? – StefanR Mar 11 '21 at 08:11
  • the methods: `ofNullable()`, `.filter()`, `.map()` and `.orElse()` are your friends here. I suggest you to look at the javadoc of each to understand how you should use them – Lino Mar 11 '21 at 08:16
  • 1
    Also: [Don't use Optionals for conditional logic.](https://stackoverflow.com/a/56235329/5515060) – Lino Mar 11 '21 at 08:27
  • 1
    In case you are trying to create an octal escape, mind that sometimes you even need to prepend `"00"`. – Holger Mar 15 '21 at 14:05

2 Answers2

4

Try this.

String result = Optional.ofNullable(valueA)
    .map(s -> s.length() < 3 ? "0" + s : s)
    .orElse(valueB);
1

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:

  • null (where valueA is null)
  • valueA
  • modified valueA
  • valueB having an object
  • valueB being null

Our call to Optional.ofNullable handles all five.

  • If null, an empty Optional is returned.
  • If non-null, a 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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    The only case handled by the `Optional` in your code is the last one, `valueB` being null. Everything else is still handled by the ternary operator. – Holger Mar 15 '21 at 14:09