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)
Algorithm. One of the most efficient ways to replace matching strings (without regular expressions) is to use the Aho-Corasick algorithm with a performant Trie (pronounced "try"), fast hashing algorithm, and efficient collections implementation.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.
A Placeholder is a predefined location in a JSP that displays a single piece of web content at a time that is dynamically retrieved from the BEA Virtual Content Repository.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With