Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

Java standard library provides the String.format() method to format a template-based string, such as: String.format(“%s is awesome”, “Java”).

In this tutorial, we'll explore how to make string formatting support named parameters.

2. Introduction to the Problem

The String.format() method is pretty straightforward to use. However, when the format() call has many arguments, it gets difficult to understand which value will come to which format specifier, for example:

Employee e = ...; // get an employee instance
String template = "Firstname: %s, Lastname: %s, Id: %s, Company: %s, Role: %s, Department: %s, Address: %s ...";
String.format(template, e.firstName, e.lastName, e.Id, e.company, e.department, e.role ... )

Further, it's error-prone when we pass those arguments to the method. For instance, in the example above, we put e.department ahead of e.role by mistake.

So, it would be great if we could use something like named parameters in the template and then apply formatting through a Map that holds all parameter name->value mappings:

String template = "Firstname: ${firstname}, Lastname: ${lastname}, Id: ${id} ...";
ourFormatMethod.format(template, parameterMap);

In this tutorial, we'll first look at a solution using a popular external library, which can solve most cases of this problem. Then, we'll discuss an edge case that breaks the solution.

Finally, we'll create our own format() method to cover all cases.

For simplicity, we'll use unit test assertions to verify if a method returns the expected string.

It's also worth mentioning that we'll only focus on simple string formats (%s) in this tutorial. Other format types, such as date, number, or a format with defined width and precision, are not supported.

3. Using StrSubstitutor From Apache Commons Text

Apache Commons Text library contains many handy utilities for working with strings. It ships with StrSubstitutor, which allows us to do string substitution based on named parameters.

First, let's add the library as a new dependency to our Maven configuration file:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

Of course, we can always find the latest version at the Maven Central repository.

Before we see how to use the StrSubstitutor class, let's create a template as an example:

String TEMPLATE = "Text: [${text}] Number: [${number}] Text again: [${text}]";

Next, let's create a test to build a string based on the template above using StrSubstitutor:

Map<String, Object> params = new HashMap<>();
params.put("text", "It's awesome!");
params.put("number", 42);
String result = StrSubstitutor.replace(TEMPLATE, params, "${", "}");
assertThat(result).isEqualTo("Text: [It's awesome!] Number: [42] Text again: [It's awesome!]");

As the test code shows, we let params hold all name -> value mappings. When we call the StrSubstitutor.replace() method, apart from template and params, we also pass the prefix and the suffix to inform StrSubstitutor what a parameter consists of in the template. StrSubstitutor will search prefix + map.entry.key + suffix for parameter names.

When we run the test, it passes. So, it seems that StrSubstitutor solves the problem.

4. An Edge Case: When Replacements Contain Placeholders

We've seen that the StrSubstitutor.replace() test passes for our basic use case. However, some special cases are not covered by the test. For example, the parameter value may contain the parameter name pattern “${ … }“.

Now, let's test this case:

Map<String, Object> params = new HashMap<>();
params.put("text", "'${number}' is a placeholder.");
params.put("number", 42);
String result = StrSubstitutor.replace(TEMPLATE, params, "${", "}");

assertThat(result).isEqualTo("Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]");

In the test above, the value of the parameter “${text}” contains the text “${number}“. So, we're expecting that “${text}” is replaced by the text “${number}” literally.

However, the test fails if we execute it:

org.opentest4j.AssertionFailedError: 
expected: "Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]"
 but was: "Text: ['42' is a placeholder.] Number: [42] Text again: ['42' is a placeholder.]"

So, StrSubstitutor treats the literal ${number} as a parameter placeholder, too.

In fact, StrSubstitutor‘s Javadoc has stated this case:

Variable replacement works in a recursive way. Thus, if a variable value contains a variable then that variable will also be replaced.

This happens because, in each recursion step, StrSubstitutor takes the last replacement result as the new template to proceed with further replacements.

To bypass this problem, we can choose different prefixes and suffixes so that they don't get interfered with:

String TEMPLATE = "Text: [%{text}] Number: [%{number}] Text again: [%{text}]";
Map<String, Object> params = new HashMap<>();
params.put("text", "'${number}' is a placeholder.");
params.put("number", 42);
String result = StrSubstitutor.replace(TEMPLATE, params, "%{", "}");

assertThat(result).isEqualTo("Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]");

However, theoretically speaking, as we cannot predict the values, it's always possible that a value contains the parameter name pattern and interferes with the replacement.

Next, let's create our own format() method to solve the problem.

5. Building the Formatter on Our Own

We've discussed why StrSubstitutor cannot handle the edge case well. So, if we create a method, the difficulty is that we shouldn't use a loop or recursion to take the last step's result as new input in the current step.

5.1. The Idea to Solve the Problem

The idea is that we search for the parameter name patterns in the template. However, when we find one, we don't replace it with the value from the map immediately. Instead, we build a new template that can be used for the standard String.format() method. If we take our example, we will try to convert:

String TEMPLATE = "Text: [${text}] Number: [${number}] Text again: [${text}]";
Map<String, Object> params ...

into:

String NEW_TEMPLATE = "Text: [%s] Number: [%s] Text again: [%s]";
List<Object> valueList = List.of("'${number}' is a placeholder.", 42, "'${number}' is a placeholder.");

Then, we can call String.format(NEW_TEMPLATE, valueList.toArray()); to finish the job.

5.2. Creating the Method

Next, let's create a method to implement the idea:

public static String format(String template, Map<String, Object> parameters) {
    StringBuilder newTemplate = new StringBuilder(template);
    List<Object> valueList = new ArrayList<>();

    Matcher matcher = Pattern.compile("[$][{](\\w+)}").matcher(template);

    while (matcher.find()) {
        String key = matcher.group(1);

        String paramName = "${" + key + "}";
        int index = newTemplate.indexOf(paramName);
        if (index != -1) {
            newTemplate.replace(index, index + paramName.length(), "%s");
            valueList.add(parameters.get(key));
        }
    }

    return String.format(newTemplate.toString(), valueList.toArray());
}

The code above is pretty straightforward. Let's walk through it quickly to understand how it works.

First, we've declared two new variables to save the new template (newTemplate) and the value list (valueList). We'll need them when we call String.format() later.

We use Regex to locate parameter name patterns in the template. Then, we replace the parameter name pattern with “%s” and add the corresponding value to the valueList variable.

Finally, we call String.format() with the newly converted template and values from valueList.

For simplicity, we've hard-coded the prefix “${” and suffixes “}” in the method. Also, if the value for a parameter “${unknown}” isn't provided, we'll simply replace the “${unknown}” parameter with “null.

5.3. Testing Our format() Method

Next, let's test if the method works for the regular case:

Map<String, Object> params = new HashMap<>();
params.put("text", "It's awesome!");
params.put("number", 42);
String result = NamedFormatter.format(TEMPLATE, params);
assertThat(result).isEqualTo("Text: [It's awesome!] Number: [42] Text again: [It's awesome!]");

Again, the test passes if we give it a run.

Of course, we want to see if it works for the edge case, too:

params.put("text", "'${number}' is a placeholder.");
result = NamedFormatter.format(TEMPLATE, params);
assertThat(result).isEqualTo("Text: ['${number}' is a placeholder.] Number: [42] Text again: ['${number}' is a placeholder.]");

If we execute this test, it passes, too! We've solved the problem.

6. Conclusion

In this article, we've explored how to replace parameters in template-based strings from a set of values. Basically, Apache Commons Text's StrSubstitutor.replace() method is pretty straightforward to use and can solve most cases. However, when values contain the parameter name patterns, StrSubstitutor may produce an unexpected result.

Therefore, we've implemented a format() method to solve this edge case.

As always, the full source code of the examples is available over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
guest
0 Comments
Inline Feedbacks
View all comments