Friday, December 25, 2020

Constrast DataWeave and Java mapping operations

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Exam Prep, Oracle Java Career

Main points:

◉ DataWeave 2.0 provides mapping capabilities

◉ Java and DataWeave can achieve the same mappings

◉ DataWeave mapping operator is less verbose than Java

DataWeave map operator

The DataWeave 2.0 (Mule 4) map operator shares similarities with the map() method from Java’s Stream class.

Mapping is a transformative operation

The idea of mapping is to transform each element of an array and output a new array of transformed elements. An expression is provided that performs the transformation. It is applied to each element in the array and collected into another new array.

Apply a mapping to an array in Java

In Java, a transformative expression is applied by passing it to the map() method of the Stream class. It is applied in turn to each element of the array and collected to a new List. In the following code snippet the inline array is transformed into a stream so that mapping can be performed.

List<String> pets = Arrays.asList(

  new String[] { "cat", "dog", "fish" }

);

List<String> newPets = pets.stream()

  .map(e -> e.toUpperCase())

  .collect(Collectors.toList());

The transformation is performed by the lambda expression e -> e.toUpperCase() where the variable e represents each element in the array. The result of the transformation is added to a new List using a collector Collectors.toList().

There is a ‘short cut’ expression that you can use in place of the explicit lambda expression. It is String::toUpperCase, the above code would now look as follows.

pets.stream()

  .map(String::toUpperCase)

  .collect(Collectors.toList());

Apply a mapping to an array in DataWeave

In DataWeave a transformative expression is applied to each element of an array and outputted to a new array containing these new transformed elements.

var pets = ["cat", "dog", "fish"]

---

pets map upper($)

Oracle Java Tutorial and Material, Oracle Java Guides, Oracle Java Exam Prep, Oracle Java Career
The upper() function is applied to each element in the pets array and transformed. Each transformed element is put into a new array. This new array is the output of this operation. The dollar ($) symbol represents each element in the array as the map function iterates over the array. The upper() function is a lambda function from the dw::Core module. It is automatically imported into all DataWeave scripts.

Final thoughts

DataWeave has been designed to transform data and does so in a performant way. The code is concise and easy to understand. As you can see Java is more verbose but provides much more capabilities than data transformation.

Related Posts

0 comments:

Post a Comment