Java: Fastest way to replace multiple string placeholder

Tamanna_24 :

What is the fastest way in java to replace multiple placeholders.

For example: I have a String with multiple placeholder, each has string placeholder name.

String testString = "Hello {USERNAME}! Welcome to the {WEBSITE_NAME}!";

And a Map which contains the map of what value will be placed in which placeholder.

Map<String, String> replacementStrings = Map.of(
                "USERNAME", "My name",
                "WEBSITE_NAME", "My website name"
        );

What is the fastest way in java to replace all the placeholder from Map. Is it possible to update all placeholders in one go?

(Please note, I cannot change the placeholder format to {1}, {2} etc)

Code_Mode :

You can try with StrSubstitutor (Apache Commons)

String testString = "Hello {USERNAME}! Welcome to the {WEBSITE_NAME}!";
Map<String, String> replacementStrings = Map.of(
                "USERNAME", "My name",
                "WEBSITE_NAME", "My website name"
        );
StrSubstitutor sub = new StrSubstitutor(replacementStrings , "{", "}");
String result = sub.replace(testString );

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116790&siteId=1