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

  1. Open tMap and click the output singleTernaryLocality column.
  2. Enter the following code:
    customer.countryOfBirth.equals("UK") ? "UK" : "RestOfWorld"
  3. 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

  1. Open tMap and click the output column multiTernaryLocality.
  2. Enter the following code:
    customer.countryOfBirth.equals("UK") ? "UK" : customer.countryOfBirth.equals("France") ? "Europe" : customer.countryOfBirth.equals("Germany") ? "Europe" :"RestOfWorld"
  3. Run the job. You should now see that France and Germany are now classified as Europe.

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:

There's more…