Home > Software design >  How I can convert Map to String?
How I can convert Map to String?

Time:05-28

This is my map:

Map<String, Object> params = new HashMap<>();
        params.put("topicRef", "update-123456-78925-new-u1z1w3");
        params.put("parentRef", "update-123456-78925-new-u1z1w3");

        Script script = new Script(ScriptType.INLINE, "painless",
                String.format("ctx._source.parentRef = params.parentRef; ctx._source.topicRef = params.topicRef"),
                params);
        request.setScript(script);

I want to convert my map into a string but I would like to change the pattern for e.g.:

"ctx._source.key = value;ctx._source.key = value"

I want to add to key value a prefix ctx._source.key and a suffix " =" (space and equal), then I would like to separate each entry with a semicolon.

CodePudding user response:

String formattedMap = params.entrySet().
        stream()
        .map(e -> "ctx._source."   e.getKey()   " = "   e.getValue())
        .collect(Collectors.joining(","));

CodePudding user response:

Try something like this:

Map<String, String> yourMap = /*...*/;
StringBuilder bob = new StringBuilder();
yourMap.forEach((key, value) -> bob.append(key).append("=").append(value).append(";"));
String result = bob.toString();

If necessary you could remove the last ; on result via String.concat().

CodePudding user response:

You could stream your Map's entries, then use the map operation to map each entry to the formatted String and ultimately join each element with the collect(Collectors.joining(";")) operation.

Map<String, Object> params = new HashMap<>();
params.put("topicRef", "update-123456-78925-new-u1z1w3");
params.put("parentRef", "update-123456-78925-new-u1z1w3");

String result = params.entrySet().stream()
        .map(entry -> String.format("%s%s%s%s", "ctx._source.", entry.getKey(), " =", entry.getValue()))
        .collect(Collectors.joining(";"));

System.out.println(result);

Here is a link to test the code

enter image description here

CodePudding user response:

String result = params.entrySet()
               .stream()
               .map(x -> "ctx._source."   x.getKey()   " = "   x.getValue())
               .reduce((x, y) -> x   ";"   y).get();
  • Related