Mule4 DataWeave Exercise: map, reduce, and pluck

Using the DataWeave exercise below, I'll demonstrate how to use the reduce, map, valuesOf, splitBy functions, format, and ++ operator.

Given Input:

JSON
 
[
    {
        "empId": "ex12345",
        "fullName": "Peter parker",
        "street": "Second Ave 46",
        "city": "San Francisco",
        "state": "veniam",
        "postal": "sit",
        "country": "Mexico",
        "dept": "hr",
        "joinedDate": "2021-12-22",
        "miles": 68
    },
    {
        "empId": "ex54321",
        "fullName": "Joseph charles",
        "street": "First Ave 47",
        "city": "Bangalore",
        "state": "Karnataka",
        "postal": "560100",
        "country": "India",
        "dept": "finance",
        "joinedDate": "2021-11-15",
        "miles": 49
    }
]

Desired Output:

JSON
 
[
  {
    "firstName": "Peter",
    "lastName": "parker",
    "AddrWithValuesOf": "San Francisco,veniam,sit,Mexico",
    "AddrWithPluck": "San Francisco,veniam,sit,Mexico",
    "miles": 68.00,
    "DateofJoin": "22-Dec-2021"
  },
  {
    "firstName": "Joseph",
    "lastName": "charles",
    "AddrWithValuesOf": "Bangalore,Karnataka,560100,India",
    "AddrWithPluck": "Bangalore,Karnataka,560100,India",
    "miles": 49.00,
    "DateofJoin": "15-Nov-2021"
  }
]

We can accomplish the desired output by writing the following DataWeave.

Java: Why a Set Can Contain Duplicate Elements

In low-latency applications, the creation of unnecessary objects is often avoided by reusing mutable objects to reduce memory pressure and thus the load on the garbage collector. This makes the application run much more deterministically and with much less jitter. However, care must be taken as to how these reused objects are used, or else unexpected results might manifest themselves, for example in the form of a Set containing duplicate elements such as [B, B].

HashCode and Equals

Java’s built-in ByteBuffer provides direct access to heap and native memory using 32-bit addressing. Chronicle Bytes is a 64-bit addressing open-source drop-in replacement allowing much larger memory segments to be addressed. Both these types provide a hashCode() and an equals() method that depends on the byte contents of the objects’ underlying memory segment. While this can be useful in many situations, mutable objects like these should not be used in most of Java’s built-in Set types and not as a key in most built-in Map types.

A List of Perl List Processing Modules

As previously written, I like list processing. Many computing problems can be broken down into transforming and filtering lists, and Perl has got the fundamentals covered with functions like map, grep, and sort. There is so much more you might want to do, though, and CPAN has a plethora of list and array processing modules.

However, due to the vicissitudes of Perl module maintenance, we have a situation where it's not clear at a glance where to turn when you've got a list that needs processing. So here's another list: the list modules of CPAN. Click through to discover what functions they provide.

DataWeave: The map Function Explained

Main Points:

  • The map function transforms data
  • If iterates over the elements in an array 
  • It applies a transformation to each element
  • Applies only to array input
  • It can only output an array

What Is the map Function Used For?

The map function is used to transform the data contained in an array. It does this by iterating over the elements in the array and applying a transformation to each element. The result of the transformation is collected together and output as an array of transformed elements. If you are familiar with Java 8 functional programming approach, a comparison can be made with the the map() method of the Stream class, find out more in my article Contrast DataWeave and Java mapping operations.

How Is the Transformation Described?

The transformation that is applied to each element is described with DataWeave. For example, to change a text value in the source array use the upper() built in function.

Java: Create a Map With Predefined Keys

This article walks you through the lean ways of creating a Map with a fixed (predefined) set of keys.

Option One: Using Lombok and Jackson

In this approach, we would create a simple class. This class would have a set of predefined fields. Once the object of this class is created, we can then use Jackson to create a map from this object.

14 Tips for Writing Spring MVC Controllers

Here are the best tips and tricks for writing Spring MVC Controllers.

In this article, I'm going to share with you some of the fundamental techniques and best practices for writing a controller class with the Spring MVC framework. Typically, in Spring MVC, we write a controller class to handle requests coming from the client.

Then, the controller invokes a business class to process business-related tasks, and then redirects the client to a logical view name, which is resolved by Spring’s dispatcher servlet in order to render results or output. That completes a round trip of a typical request-response cycle.

Converting Objects to Map and Back

In large enterprise applications, sometimes, we need to convert data objects to and from Map. Usually, it is an intermediate step to a special serialization. If it is possible to use something standard, then it is better to use that, but many times, the architecture envisioned by some lead architect, the rigid environment, or some similar reason does not make it possible to use JOOQ, Hibernate, Jackson, JAX, or something similar. In such a situation, as it happened to me a few years ago, we have to convert the objects to some proprietary format being string or binary, and the first step towards that direction is to convert the object to a Map.

Eventually, the conversion is more complex than just:

An Illustrated (and Musical) Guide to Map, Reduce, and Filter Array Methods

Map, reduce, and filter are three very useful array methods in JavaScript that give developers a ton of power in a short amount of space. Let’s jump right into how you can leverage (and remember how to use!) these super handy methods.

Array.map()

Array.map() updates each individual value in a given array based on a provided transformation and returns a new array of the same size. It accepts a callback function as an argument, which it uses to apply the transform.

let newArray = oldArray.map((value, index, array) => {
  ...
});

A mnemonic to remember this is MAP: Morph Array Piece-by-Piece.

Instead of a for-each loop to go through and apply this transformation to each value, you can use a map. This works when you want to preserve each value, but update it. We’re not potentially eliminating any values (like we would with a filter), or calculating a new output (like we would use reduce for). A map lets you morph an array piece-by-piece. Let’s take a look at an example:

[1, 4, 6, 14, 32, 78].map(val => val * 10)
// the result is: [10, 40, 60, 140, 320, 780]

In the above example, we take an initial array ([1, 4, 6, 14, 32, 78]) and map each value in it to be that value times ten (val * 10). The result is a new array with each value of the original array transformed by the equation: [10, 40, 60, 140, 320, 780].

An illustration of the code examples covered in this section.

Array.filter()

Array.filter() is a very handy shortcut when we have an array of values and want to filter those values into another array, where each value in the new array is a value that passes a specific test.

This works like a search filter. We’re filtering out values that pass the parameters we provide.

For example, if we have an array of numeric values, and want to filter them to just the values that are larger than 10, we could write:

[1, 4, 6, 14, 32, 78].filter(val => val > 10)
// the result is: [14, 32, 78]

If we were to use a map method on this array, such as in the example above, we would return an array of the same length as the original with val > 10 being the “transform," or a test in this case. We transform each of the original values to their answer if they are greater than 10. It would look like this:

[1, 4, 6, 14, 32, 78].map(val => val > 10)
// the result is: [false, false, false, true, true, true]

A filter, however, returns only the true values. So the result is smaller than the original array or the same size if all values pass a specific test.

Think about filter like a strainer-type-of-filter. Some of the mix will pass through into the result, but some will be left behind and discarded.

An illustration of a funnel with numbers going in the top and a few coming out of the bottom next to a handwritten version of the code covered in this section.

Say we have a (very small) class of four dogs in obedience school. All of the dogs had challenges throughout obedience school and took a graded final exam. We’ll represent the doggies as an array of objects, i.e.:

const students = [
  {
    name: "Boops",
    finalGrade: 80
  },
  {
    name: "Kitten",
    finalGrade: 45
  },
  {
    name: "Taco",
    finalGrade: 100
  },
  {
    name: "Lucy",
    finalGrade: 60
  }
]

If the dogs get a score higher than 70 on their final test, they get a fancy certificate; and if they don’t, they’ll need to take the course again. In order to know how many certificates to print, we need to write a method that will return the dogs with passing grades. Instead of writing out a loop to test each object in the array, we can shorten our code with filter!

const passingDogs = students.filter((student) => {
  return student.finalGrade >= 70
})

/*
passingDogs = [
  {
    name: "Boops",
    finalGrade: 80
  },
  {
    name: "Taco",
    finalGrade: 100
  }
]
*/

As you can see, Boops and Taco are good dogs (actually, all dogs are good dogs), so Boops and Taco are getting certificates of achievement for passing the course! We can write this in a single line of code with our lovely implicit returns and then remove the parenthesis from our arrow function since we have single argument:

const passingDogs = students.filter(student => student.finalGrade >= 70)

/*
passingDogs = [
  {
    name: "Boops",
    finalGrade: 80
  },
  {
    name: "Taco",
    finalGrade: 100
  }
]
*/

Array.reduce()

The reduce() method takes the input values of an array and returns a single value. This one is really interesting. Reduce accepts a callback function which consists of an accumulator (a value that accumulates each piece of the array, growing like a snowball), the value itself, and the index. It also takes a starting value as a second argument:

let finalVal = oldArray.reduce((accumulator, currentValue, currentIndex, array) => {
  ...
}), initalValue;
An illustration of a saucepan cooking ingredients next to handwritten code from the examples covered in this section.

Let’s set up a cook function and a list of ingredients:

// our list of ingredients in an array
const ingredients = ['wine', 'tomato', 'onion', 'mushroom']

// a cooking function
const cook = (ingredient) => {
    return `cooked ${ingredient}`
}

If we want to reduce the items into a sauce (pun absolutely intended), we’ll reduce them with reduce()!

const wineReduction = ingredients.reduce((sauce, item) => {
  return sauce += cook(item) + ', '
  }, '')
  
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom, "

That initial value ('' in our case) is important because if we don’t have it, we don’t cook the first item. It makes our output a little wonky, so it’s definitely something to watch out for. Here’s what I mean:

const wineReduction = ingredients.reduce((sauce, item) => {
  return sauce += cook(item) + ', '
  })
  
// wineReduction = "winecooked tomato, cooked onion, cooked mushroom, "

Finally, to make sure we don’t have any excess spaces at the end of our new string, we can pass in the index and the array to apply our transformation:

const wineReduction = ingredients.reduce((sauce, item, index, array) => {
  sauce += cook(item)
  if (index < array.length - 1) {
        sauce += ', '
        }
        return sauce
  }, '')
  
// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"

Now we can write this even more concisely (in a single line!) using ternary operators, string templates, and implicit returns:

const wineReduction = ingredients.reduce((sauce, item, index, array) => {
  return (index < array.length - 1) ? sauce += `${cook(item)}, ` : sauce += `${cook(item)}`
}, '')

// wineReduction = "cooked wine, cooked tomato, cooked onion, cooked mushroom"

A little way to remember this is to recall how you make sauce: you reduce a few ingredients down to a single item.

Sing it with me!

I wanted to end this blog post with a song, so I wrote a little diddy about array methods that might just help you to remember them:

The post An Illustrated (and Musical) Guide to Map, Reduce, and Filter Array Methods appeared first on CSS-Tricks.

Enum Tricks: Two Ways to Extend Enum Functionality

In my previous article, I explained how and why to use enumsinstead of the switch/case control structure in Java code. Here, I will demonstrate how to extend the functionality of existing enums.

Introduction

Java enumis a kind of a compiler magic. In byte code, any enum is represented as a class that extends the abstract class java.lang.Enum and has several static members. Therefore, enum cannot extend any other class orenum: there is no multiple inheritance.

One Method to Rule Them All: Map.merge()

 I don’t often explain a single method in JDK, but when I do, it’s about Map.merge(). This is probably the most versatile operation in the key-value universe. But it's also rather obscure and rarely used.

merge() can be explained as follows: it either puts new value under the given key (if absent) or updates existing key with a given value (UPSERT). Let’s start with the most basic example: counting unique word occurrences. Pre-Java 8 (read: pre-2014!) code was quite messy and the essence was lost in implementation details: