-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,777
  • 4
  • 31
  • 53

3 Answers3

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,419
  • 3
  • 4
  • 13
0

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
  • 1,856
  • 3
  • 10
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
  • 197
  • 14