StringSubstitutor from Apache Commons Text library is a lightweight way of doing this, provided your values are already formatted correctly.

Map<String, String> values = new HashMap<>();
values.put("value", "1");
values.put("column","2");

StringSubstitutor sub = new StringSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");

The result string will contain the following:

There's an incorrect value '1' in column # 2

When using Maven you can add this dependency to your pom.xml:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.10.0</version>
</dependency>
Answer from schup on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java string › named placeholders in string formatting
Named Placeholders in String Formatting | Baeldung
August 27, 2025 - Basically, Apache Commons Text’s StringSubstitutor.replace() method is pretty straightforward to use and can solve most cases. However, when values contain the parameter name patterns, StringSubstitutor may produce an unexpected result. Therefore, we’ve implemented a format() method to solve this edge case.
Discussions

Java string templatizer / formatter with named arguments - Stack Overflow
Is there a standard or at least widespread implementation of something like String.format, but with named arguments? I'd like to format a templatized string in a way like that: Map More on stackoverflow.com
🌐 stackoverflow.com
A simple string formatter that supports named arguments and limited "object introspection" at the template level.

Am i only one who does not quite like this? :)

Usually with similar helpers you got the part "How" and then next "What". Imho mixing them together is only asking for troubles

More on reddit.com
🌐 r/java
5
10
April 3, 2017
java - How to format message with argument names instead of numbers? - Stack Overflow
Java's string templates are more versatile, and much safer, than features in other languagues such as C#'s string interpolation and Python's f-strings. For example, string concatenation or interpolation makes SQL injection attacks possible: CopyString query = "SELECT * FROM Person p WHERE p.last_name ... More on stackoverflow.com
🌐 stackoverflow.com
String template with named placeholders
Thanks for all responses, please note, My question was specifically for named placeholders not positional, and I am looking for a template system, i.e. something to be able to reuse and plug in different values, not for an interpolated string where the variables have to be predefined in scope More on reddit.com
🌐 r/learnprogramming
7
1
July 14, 2022
Top answer
1 of 1
6

Performing string substitutions using multiple passes is almost always the wrong approach, and leads to bugs. If one of the values happens to be a string that looks like a %(key), then all sorts of unpredictable things could happen, including various uncontrolled format string attacks!

Therefore, the string replacements must be done in a single pass of the format string. I recommend doing it using a regular expression.

Furthermore, your method provides no escape mechanism, in case you need to specify a literal %(blah) in the format string. In Java, it would be customary to use backslash as an escape character.

Suggested solution

This solution uses Matcher.replaceAll(Function<MatchResult,String> replacer), which was introduced in Java 9, to provide each substitution text via a callback.

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NamedFormatter {
    private static final Pattern RE = Pattern.compile(
        "\\\\(.)" +         // Treat any character after a backslash literally 
        "|" +
        "(%\\(([^)]+)\\))"  // Look for %(keys) to replace
    );

    private NamedFormatter() {}

    /**
     * Expands format strings containing <code>%(keys)</code>.
     *
     * <p>Examples:</p>
     *
     * <ul>
     * <li><code>NamedFormatter.format("Hello, %(name)!", Map.of("name", "200_success"))</code> → <code>"Hello, 200_success!"</code></li>
     * <li><code>NamedFormatter.format("Hello, \%(name)!", Map.of("name", "200_success"))</code> → <code>"Hello, %(name)!"</code></li>
     * <li><code>NamedFormatter.format("Hello, %(name)!", Map.of("foo", "bar"))</code> → <code>"Hello, %(name)!"</code></li>
     * </ul>
     *
     * @param fmt The format string.  Any character in the format string that
     *            follows a backslash is treated literally.  Any
     *            <code>%(key)</code> is replaced by its corresponding value
     *            in the <code>values</code> map.  If the key does not exist
     *            in the <code>values</code> map, then it is left unsubstituted.
     *
     * @param values Key-value pairs to be used in the substitutions.
     *
     * @return The formatted string.
     */
    public static String format(String fmt, Map<String, Object> values) {
        return RE.matcher(fmt).replaceAll(match ->
            match.group(1) != null ?
                match.group(1) :
                values.getOrDefault(match.group(3), match.group(2)).toString()
        );
    }
}
🌐
Igor's Techno Club
igorstechnoclub.com › java-string-format
Mastering Java String Format – Igor's Techno Club
May 20, 2024 - While Java doesn't natively support named parameters in string formatting, you can achieve a similar effect using the java.text.MessageFormat class (for detailed exploration of the MessageFormat follow the link):
🌐
Belief Driven Design
belief-driven-design.com › looking-at-java-21-string-templates-c7cbc
Looking at Java 21: String Templates | belief driven design
June 20, 2023 - String formatted(Object... args) (Java 15+) They allow for reusable templates, but they require format specifiers and provide the variables in the correct order: ... var format = "Hello %s, how are you?\nIt's %d°C today!"; var greeting = String.format(format, name, tempC); // Java 15+ var greeting = format.formatter(name, tempC);
🌐
TikTok
tiktok.com › discover › string-format-named-parameters-java
String Format Named Parameters Java | TikTok
April 27, 2026 - Java strings tutorial, Java string manipulation techniques, understanding strings in Java, Java development best practices, advanced string handling in Java, Java programming tips, string operations in Java, Java coding exercises, Java string performance, effective Java string management ... string.format refers to a method or function used in various programming languages to create formatted strings by embedding values into a template string.
🌐
Oracle
docs.oracle.com › cd › E16162_01 › apirefs.1112 › e17493 › oracle › javatools › resourcebundle › NamedMessageFormat.html
NamedMessageFormat (Oracle Fusion Middleware Java API Reference for Oracle Extension SDK)
The NamedMessageFormat class is a greatly reduced version of the java.text.MessageFormat class, supporting named-parameter replacement instead of index-based replacement.
Find elsewhere
🌐
Scaler
scaler.com › home › topics › java string interpolation
Java String Interpolation - Scaler Topics
December 20, 2022 - There are primarily five ways to implement Java String Interpolation, which includes using plus (+) operator, String.format() method, MessageFormat class, and StringBuilder class.
🌐
GitHub
gist.github.com › manzke › 6856743
A class to format message which contain named parameters like "send an email from {sender} to {recipient}". · GitHub
A class to format message which contain named parameters like "send an email from {sender} to {recipient}". Raw · Templating.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Formatter.html
Formatter (Java Platform SE 8 )
July 21, 2026 - public Formatter(String fileName, String csn) throws FileNotFoundException, UnsupportedEncodingException · Constructs a new formatter with the specified file name and charset. The locale used is the default locale for formatting for this instance of the Java virtual machine.
🌐
Reddit
reddit.com › r/learnprogramming › string template with named placeholders
r/learnprogramming on Reddit: String template with named placeholders
July 14, 2022 -

Imagine the following piece of code

Template("Hello {name}, you are {position} in line").format(name="Alice", position=12, extra=42) 

Would you rather that an error be thrown due to an unbound key (extra) being passed or should it be ignored?

I didn't find much languages even having such string templating built in except other than Python (string.format) and Rust (format!), in Python the extra key/value is ignored, while Rust will throw an exception.

What would be your approach?

Top answer
1 of 2
1
Thanks for all responses, please note, My question was specifically for named placeholders not positional, and I am looking for a template system, i.e. something to be able to reuse and plug in different values, not for an interpolated string where the variables have to be predefined in scope
2 of 2
1
There are 'format strings' in many languages... eg. Java "Hello %s, you are %d in line".formatted("Alice", 12, 42) I think many languages silently ignore the unbound param (though many IDE's can report it) - since the params list might not be dynamic (that is it may be a literal param list in the code as opposed to data), but the formatting template could be dynamic. An alternative is String Interpolation, which is available in many languages. Java, which lacks it, is investigating adding the feature - from their feature proposal we can see the following: Language | Example | JavaScript | ${x} plus ${y} equals ${x + y} (uses backticks) | C# | $"{x} plus {y} equals {x + y}" | Visual Basic | $"{x} plus {y} equals {x + y}" | Scala | f"$x%d plus $y%d equals ${x + y}%d" | Python | f"{x} plus {y} equals {x + y}" | Ruby | "#{x} plus #{y} equals #{x + y}" | Groovy | "$x plus $y equals ${x + y}" | Kotlin | "$x plus $y equals ${x + y}" | Swift | "(x) plus (y) equals (x + y)" I think Rust would be something like format!("{} plus {} equals {}", x, y, x + y) or format!("{x} plus {y} equals {}", x + y) The types of expressions and formatting specifiers that can be embedded in the template itself vary a lot by language. Java is proposing something like STR."\{x} + \{y} = \{x + y}" The STR. prefix exists because the feature is expandable to include other consumers of the template that might want to do different enforcement / checking and produce a type other than a String - eg an SQL processor validating/escaping the SQL, and generating an SQL request with the expressions as SQL params instead of literals. In many cases, a benefit of interpolation is not just readability/brevity, but also that the validation is a compile-time exercise and I expect most compile-time languages would expect unbound params or values to be a compile-time error. Edit: Actually include the String Template proposal link.
🌐
Baeldung
baeldung.com › home › java › java string › guide to java.util.formatter
Guide to java.util.Formatter | Baeldung
January 8, 2024 - A template is a String that contains some static text and one or more format specifiers, which indicate which argument is to be placed at the particular position. In this case, there’s a single format specifier %s, which gets replaced by the corresponding argument.
🌐
BeginnersBook
beginnersbook.com › 2017 › 10 › java-string-format-method
Java String format() method
June 9, 2024 - public class Example{ public static void main(String args[]){ String name = "Chaitanya"; int age = 37; double luckyNum = 123.456; String formattedString = String.format("Name: %s, Age: %d, Lucky No: $%.2f", name, age, luckyNum); System.out.println(formattedString); // Output: Name: Chaitanya, Age: 37, Lucky No: $123.456 } } import java.util.Date; public class Example{ public static void main(String args[]){ Date date = new Date(); String formattedDate = String.format("Current DateTime: %tc", date); System.out.println(formattedDate); // Output: Current DateTime: Sat Jun 08 07:39:52 PDT 2024 } }
🌐
Alvin Alexander
alvinalexander.com › blog › post › java › use-string-format-java-string-output
Java String formatting with the String.format method (like ‘sprintf’) | alvinalexander.com
July 30, 2024 - One way to format Java string output is with the format method of the String class, which works like a “Java sprintf” method.
🌐
DZone
dzone.com › data engineering › data › comprehensive guide to java string formatting
Comprehensive Guide to Java String Format in 2021 - DZone
July 15, 2021 - If the supplied argument does not contain enough characters after formatting, spaces are used to fulfill the minimum width. For example, if the format specifier s is used and the String name is supplied, six trailing spaces will be added to pad the result to fulfill the minimum width of 10 characters.
🌐
Blogger
javaexplorer03.blogspot.com › 2016 › 05 › java-message-format-using-named.html
java explorer: Java Message Format Using Named Placeholder
May 20, 2016 - The Java MessageFormat class allows user to pre-define a string with placeholders and then fill the placeholders with actual strings later to construct a proper message. It's all fine if you're used to numbered placeholders e.g. {0} and {1}. Apache Commons has a StrSubstitutor class which allows ...