Reading Time: 9 minutes

In Mule 4, DataWeave is everywhere: every listener and processor can be configured with it. Because most Mule users already know Java well, this article will help Java developers to easily use DataWeave by rewriting their lambdas expressions.

First, I will show why lambdas were created and explain the historical context. Next, I’ll explain the important point of when to use lambdas and when to not use lambdas. To conclude, I’ll show where you can use lambdas in your DataWeave code.

Why lambdas

latest report
Learn why we are the Leaders in API management and iPaaS

Lambdas were first introduced with the Java 8 release in order to simplify the Java code. We will compare: 

  • the Java code without lambdas
  • the Java code with lambdas
  • the DataWeave 2.0 with lambdas

We will work with the following use case: “We want to order a list of Java Objects given criteria.”

Let’s first define a simple class for the objects we want to order:

package com.mulesoft.training;

public class Customer {

private String lastName;
private String firstName;
private int age;

public Customer(String lastName, String firstName, int age) {
setLastName(lastName);
setFirstName(firstName);
setAge(age);
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return(getLastName()+" "+getFirstName()+" ("+getAge()+")");
}
}

Now we can create samples to work within both Java and DataWeave.

table { padding: .5px; } th, td { border: 1px solid black; padding: 10px; }
ArrayList array = new ArrayList<>();

array.add(new Customer("Simpson","Homer",39));
array.add(new Customer("Simpson","Lisa",8));
array.add(new Customer("Simpson","Bart",10));
array.add(new Customer("Simpson","Marge",36));
array.add(new Customer("Simpson","Maggie",1));
var array = 
[
{"lastName":"Simpson",
"firstName":"Homer",
"age":39
},
{"lastName":"Simpson",
"firstName":"Lisa",
"age": 8
},
{"lastName":"Simpson",
"firstName":"Bart",
"age":10
},
{"lastName":"Simpson",
"firstName":"Marge",
"age":36
},
{"lastName":"Simpson",
"firstName":"Maggie",
"age": 1
}
]

Now let’s create the code to sort our array of objects by age. We can compare the following three ways: Java without lambdas, Java with lambdas, and DataWeave with lambdas.

table { border: 1px solid black; padding: .5px; } th, td { border: 1px solid black; padding: 10px; }
Java without lambdas Java with lambdas DataWeave with lambdas
package com.mulesoft.training;
import java.util.Comparator;

public class CustomerComparator implements Comparator {
  @Override
  public int compare(Customer c1, Customer c2) {
    return
      c1.getAge()-c2.getAge();
  }
}

Collections.sort(array, 
    new CustomerComparator());
Collections.sort(array,
(Customer c1, Customer c2) -> (c1.getAge()-c2.getAge()));
array orderBy ((item, index) -> item.age)

Please notice that we only need the Comparator class in Java code when not using lambdas.

To summarize, let’s the code length by counting the number of characters in each case:

  • 305: the Java code without lambdas
  • 84: the Java code with lambdas
  • 41: the DataWeave 2.0 with lambdas

I think it is safe to conclude that lambdas minimize code length substantially.

When to use lambdas

In the previous section, we saw how lambdas simplify our code. Without lambdas, we had to create a Java utility class named CustomerComparator. That class implemented the Comparator interface and is only composed of one method. This is when we can use a lambda in Java.

Additionally, we might consider using a lambda in these cases:

  • When the code is trivial
  • When we don’t want to reuse the code in another location — a lambda is also called an “anonymous function”

A typical use case for lambdas is to execute an action when a button is pressed in a GUI (Graphical User Interface). In effect, the code attached to a button in a GUI has a low chance of re-use.

In DataWeave the more important reason for when to use a lambda expression is that we don’t want to reuse the code. Below is an anti-pattern followed by the correct way to write it:

table { border: 1px solid black; padding: .5px; } th, td { border: 1px solid black; padding: 10px; }
Anti-pattern (give a name to a lambda) Best practice (create a function)
var compare = (c1: Object, c2: Object) -> 
  c1.age - c2.age
fun compare(c1: Object, c2: Object) = 
  c1.age - c2.age

Anti-pattern use of lambdas due to reuse, in this case, the best practice is to create a function.

Where to use lambdas

The response to “where” to use lambdas is quite simple:

  • Use a lambda as a parameter to a method/function when we don’t want to reuse code

Of course, the method/function must accept a lambda as argument.

The following table shows where it is allowed to use a lambda in functions from the DataWeave’s Core package (dw::Core).

table, th{ border: .1px solid black; } table, td{ border: .5px solid black;
++ filterObject isInteger max random sqrt write
find isLeapYear maxBy randomInt startsWith zip
abs flatMap isOdd min read sum
avg flatten joinBy minBy readUrl to
ceil floor log mod reduce trim
contains groupBy lower native replace typeOf
daysBetween isBlank map now round unzip
distinctBy isDecimal mapObject orderBy scan upper
endsWith isEmpty match pluck sizeOf uuid
filter isEven matches pow splitBy with

Conclusion

In this article, I gave an overview of why, when, and where to use lambdas in DataWeave. If you want to learn more about DataWeave 2.0, you can register for the DataWeave course.