-1

I am working on a project built on Java. I have a use case where I have multiple templates of strings that need to be formatted by replacing keywords with their values.

Since the position of parameter and name of the parameter is not always known and will change over time I want to write a function that takes a string and replace keywords (named parameter) with their values using the map.

For e.g.

Hi my name is %name

And if I have map = {"name":"user1"}

Then my function should replace the name with user1.

I tried to find if there is already an existing method or library in java but I couldn't find any.

Amir Dora.
  • 2,831
  • 4
  • 40
  • 61
  • Can you share your code with us – Aalexander Feb 20 '21 at 12:18
  • 1
    Does this answer your question? [Java generating Strings with placeholders](https://stackoverflow.com/questions/17364632/java-generating-strings-with-placeholders) – SRJ Feb 20 '21 at 12:30

3 Answers3

1

Maybe you need something like that (using a map and replacing all occurrences of keys starting with %):

Map<String, String> map= new HashMap();
map.put("name1", "user1");
map.put("name2", "user2");

String str = "Hi my name is %name1. Hi my name is %name2 and %name1";

String result = map.keySet()
                   .stream()
                   .reduce(str, (s, e) -> s.replaceAll("%"+e+"\\b", map.get(e)));
    
System.out.println(result);
Sergey Afinogenov
  • 2,137
  • 4
  • 13
0

I think you need that:

String name = "Chack";//you will get its field from your map = {"name":"user1"}
String.format("Hi my name is %s", name);
Dmitrii B
  • 2,672
  • 3
  • 5
  • 14
0

U can use simply String.format:

String name = "Example"
String.format("Hi my name is %s", name);

Or message format:

String exampleTemplate = "Hi my name is {0}";
String name = "Example Name"
String message = MessageFormat.format(exampleTemplate, name);
Oskar
  • 379
  • 4
  • 21