Anand Anand - 1 year ago 113
Java Question

Java - Append quotes to strings in an array and join strings in an array

I would like to append double quotes to strings in an array and then later join them as a single string (retaining the quotes). Is there any String library which does this? I have tried Apache commons StringUtils.join and the Joiner class in Google guava but couldn't find anything that appends double quotes.

My input would be an array as mentioned below:

String [] listOfStrings = {"day", "campaign", "imps", "conversions"};

Required output should be as mentioned below:

String output = "\"day\", \"campaign\", \"imps\", \"conversions\"";

I know I can loop through the array and append quotes. But I would like a more cleaner solution if there is one.

Answer Source

With Guava, there are two solutions:

Solution 1:

Function<String,String> addQuotes = new Function<String,String>() {
  @Override public String apply(String s) {
    return new StringBuilder(s.length()+2).append('"').append(s).append('"').toString();
String result = Joiner.on(", ").join(Iterables.transform(listOfStrings, addQuotes));

Solution 2: (this solution is absolutely discouraged for the reasons mentioned in the comments)

String result = Joiner.on("\", \"").join(listOfStrings);
if (!listOfStrings.isEmpty()) {
  result = "\"" + result + "\"";

With Java 8, it's become much simpler, but I provide two other solutions:

Solution 3:

Function<String,String> addQuotes = (s) -> new StringBuilder(s.length()+2).append('"').append(s).append('"').toString();

String result =
  .collect(Collectors.joining(", "));

Solution 4: (without a reusable function)

String result =
  .map((s) -> "\"" + s + "\"")
  .collect(Collectors.joining(", "));

Note: all the solutions assume that listOfStrings is a List<String> rather than a String[]. You can convert a String[] into a List<String> using Arrays.asList(arrayOfStrings).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download