Home > Mobile >  Stringbuildier in loop, anything to do better?
Stringbuildier in loop, anything to do better?

Time:01-29

For each x Strings the output should be in quote and each String should be separated by a comma:

For example:

input: String String1 String2
output: "String","String1","String2"

input: String
output: "String"

TestBuildier testBuildier = new TestBuildier();
    testBuildier.concatString("Test","Test1","Test2");
}

public void concatString(String...value){
        StringBuilder newValue = new StringBuilder();
        for(String str: value){
            newValue.append("\"").append(str).append("\",");
        }
        newValue.deleteCharAt(newValue.length()-1);
        System.out.println(newValue);

    }

Output is "String","String1","String2" so it works. But I'm wondering maybe u guys would do here something different or this code looks ok?

CodePudding user response:

You could also do this with a Stream:

import java.util.Arrays;
import java.util.stream.Collectors;

String result = Arrays.stream(value)
                .map(s -> '"'   s   '"')
                .collect(Collectors.joining(","));

CodePudding user response:

Just use String.join:

System.out.println('"'   String.join("\",\"", values)   '"');
  • Related