DataWeave function chaining for Java programmers

In this article, you will learn how to use method chaining in DataWeave with reference to Java 8 lambda expressions and how to convert from Java Streams into DataWeave chaining. 

Java 8 introduced the Stream API, which is used to process a stream of objects. Various methods can be chained together such as filter, limit, map, and reduce, and operate on a pipeline of objects. To learn more about lambdas, read DataWeave Lambdas for Java programmers.

Getting started

To get started we need some sample data to work with and a Java class.

Sample DataWeave data

We will use the JSON array below in the DataWeave expressions we will write. As you can see its an array of five JSON objects representing members of the Simpson family.

Sample Java class and data

The simple Customer Java class contains a static factory method that returns a List of Customer objects populated with the same data as shown in the JSON array above.

From Java Streaming to DataWeave function chaining

Now, we have the data and class needed, let’s start with reviewing how the Stream API is used to process a pipeline of data. 

Java Streams

To use chained method on a Collection in Java, we first need to create an instance of the Stream API, then we can start to chain methods together to process a data stream.

In the following example, a Stream is created from the List returned by calling the createSample() method on the Customer class and a filter is applied to each object that removes any object where the age property is less than or equal to 18. Then each object is printed to the console.

Two members of the Simpson family remain after filtering: Marge and Homer.

DataWeave function chaining

To replicate function chaining in DataWeave there is just one requirement: the function must take exactly two arguments:

  • The first argument is the object to work with, in our case, the array of customers.
  • The second argument must be a lambda function that describes how each element in the data stream is to be processed, in our case we want to filter based on age, so therefore we use the filter function.

In DataWeave there are two ways to apply a filter.

Furthermore, DataWeave allows a simplification of the lambda expression by deleting the “->.” In which case, the first argument of the lambda expression is replaced by $, and the second argument by $$.

With such simplified notation it is now really easy to chain multiple functions.

The DataWeave expression above performs the same process as the Java code described earlier.

Conclusion

In this article, we saw how a Java programmer can easily convert code containing method chaining into similar DataWeave code using function chaining.

If you want to know more about DataWeave 2.0,  register for the DataWeave training course.



We'd love to hear your opinion on this post