Thursday 21 March 2024

Print the most repetitive character in a string ? in MuleSoft178

 Print the most repetitive character in a string ? in MuleSoft

Here's a DataWeave expression you can use in MuleSoft 4 to print the most repetitive character in a string:

%dw 2.0
output application/json

var str = "This is a sample string";

// Create a map to store character counts
var charCounts = str |> tokenize("", true) groupBy $ -> $
                  reduce (acc, item) -> acc ++ { (item): acc.get(item, 0) + 1 };

// Find the character with the highest count (excluding spaces)
var mostRepetitive = charCounts filter $ != ' ' reduce (max, item) -> max > item.value ? max : item;


  "mostRepetitive": mostRepetitive.key // Output: "s"


  1. Define the String: The str variable holds the sample string for demonstration.

  2. Character Counts:

  • We use tokenize("", true) to split the string into individual characters (including spaces).

  • The groupBy $ -> $ expression groups these characters together, creating a map where each character is a key and its count is the value.

  • We then use reduce to iterate over the grouped characters and add 1 to the count for each occurrence. This builds the charCounts map.

  1. Filter Spaces:

  • The .filter $ != ' ' part filters out the space character from the charCounts map. Spaces might be the most frequent character, but we're typically interested in non-whitespace characters.

  1. Find Maximum Count:

  • We leverage reduce again, but this time to find the character with the highest count in the filtered charCounts.

  • The comparison within the reduce expression checks if the current maximum count (max) is greater than the current item's value (item.value). If it is, the maximum remains unchanged. Otherwise, the current item becomes the new maximum. This identifies the character with the highest count after excluding spaces.

  1. Extract Key (Character):

  • Finally, we access the key property of the mostRepetitive variable, which holds the character with the highest count. This gives you the most repetitive character in the string (excluding spaces).

Running the Expression:

Place this DataWeave expression within a Mule flow using a Message Transformer component. The output will be a JSON object with the "mostRepetitive" property containing the character that appears the most frequently in the string (excluding spaces).

No comments:

Post a Comment

Note: only a member of this blog may post a comment.