Using the ternary operator for conditional logic
The previous recipe mentions that a tMap
expression cannot be more than a single line of Java code. This means that we cannot use the normal if-then-else logic to test for conditions.
Fortunately, Java does provide a mechanism by which we can perform tests on a single line: the ternary expression.
Getting ready
Open the job jo_cook_ch04_0030_ternaryExpressions
.
How to do it...
We'll be looking at two similar scenarios using the ternary expression.
Single ternary expression: if-then-else
Open
tMap
and click the outputsingleTernaryLocality
column.Enter the following code:
customer.countryOfBirth.equals("UK") ? "UK" : "RestOfWorld"
Run the job. You will see that all countries apart from the UK have a locality of
RestOfWorld
.
Ternary in ternary: if-then-elsif-then-else
Open
tMap
and click the output columnmultiTernaryLocality
.Enter the following code:
customer.countryOfBirth.equals("UK") ? "UK" : customer.countryOfBirth.equals("France") ? "Europe" : customer...