- Talend Open Studio Cookbook
- Rick Barton
- 325字
- 2025-03-31 04:04:58
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.
- Open
tMap
and click the output columnmultiTernaryLocality
. - Enter the following code:
customer.countryOfBirth.equals("UK") ? "UK" : customer.countryOfBirth.equals("France") ? "Europe" : customer.countryOfBirth.equals("Germany") ? "Europe" :"RestOfWorld"
- Run the job. You should now see that
France
andGermany
are now classified asEurope
.
How it works…
The Java ternary expression is the equivalent to an if-then-else
statement in Java, but on a single line. If we were coding in Java, the test for locality would look like the following:
outputRow.locality = customer.countryOfBirth.equals("UK") ? "UK" : "RestOfWorld"
or we could write it longhand as:
if (customer.countryOfBirth.equals("UK")) { output_row.locality="UK"; }else{ output_row.locality="RestOfWorld" }
It also happens that the ternary else
clause ':'
can also be a ternary expression, thus enabling more complex if-then-elseif-then-else
type expressions.
There's more…
As with all coding constructs, beware of making them too complex, otherwise they may become un-maintainable. If you have many levels of ternary expressions, then it is probably time to consider using code
routine
or performing the logic in tJavaRow
.
If you do use multilevel ternary expressions, then they can be broken over many lines and commented appropriately using /*……*/
comments. This usually makes the code easier to understand. An example is shown in the following screenshot:
