replace two ternary operator by java 8 optional expression

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 ?

Answer

Try this.

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

Leave a Reply

Your email address will not be published. Required fields are marked *