Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Fastest way to replace multiple string placeholder

Tags:

java

string

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)

like image 721
Tamanna_24 Avatar asked Apr 19 '19 13:04

Tamanna_24


People also ask

How do you replace multiple occurrences of a string in Java?

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.

How do you add a placeholder to a string?

The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

What is place holder in Java?

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.


1 Answers

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 );
like image 165
Vikas Yadav Avatar answered Oct 26 '22 17:10

Vikas Yadav