53

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.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Anand
  • 1,791
  • 5
  • 23
  • 41

7 Answers7

139

With Java 8+

Java 8 has Collectors.joining() and its overloads. It also has String.join.

Using a Stream and a Collector

The naive but effective way

String wrapWithQuotesAndJoin(List<String> strings) {
  return strings.stream()
    .map(s -> "\"" + s + "\"")
    .collect(Collectors.joining(", "));
}

Shortest and probably better performing (somewhat hackish, though)

String wrapWithQuotesAndJoin(List<String> strings) {
  return strings.stream()
    .collect(Collectors.joining("\", \"", "\"", "\""));
}

Using String.join

Very hackish. Don't use. (but it must be mentioned)

String wrapWithQuotesAndJoin(List<String> strings) {
  return strings.isEmpty() ? "" : "\"" + String.join("\", \"", strings) + "\""
}

With older versions of Java

Do yourself a favor and use a library. Guava comes immediately to mind.

Using Guava

private static final 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 wrapWithQuotesAndJoin(List<String> strings) {     
    return Joiner.on(", ").join(Iterables.transform(listOfStrings, addQuotes));
}

No libraries

String wrapWithQuotesAndJoin(List<String> strings) {
  if (listOfStrings.isEmpty()) {
    return "";
  }
  StringBuilder sb = new StringBuilder();
  Iterator<String> it = listOfStrings.iterator();
  sb.append('"').append(it.next()).append('"'); // Not empty
  while (it.hasNext()) {
    sb.append(", \"").append(it.next()).append('"');
  }
  result = sb.toString();
}

Notes:

  • All the solutions assume that strings is a List<String> rather than a String[]. You can convert a String[] into a List<String> using Arrays.asList(strings). You can get a Stream<String> directly from a String[] using Arrays.stream(strings).
  • The Java 8+ snippets use the + concatenation because at this point + is usually better performing than StringBuilder.
  • The older-version snippets use StringBuilder rather than + because it's usually faster on the older versions.
Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137
13
String output = "\"" + StringUtils.join(listOfStrings , "\",\"") + "\"";
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
Sifeng
  • 713
  • 9
  • 23
3

Add the quotes along with the separator and then append the quotes to the front and back.

"\"" + Joiner.on("\",\"").join(values) + "\""
Tom
  • 16,842
  • 17
  • 45
  • 54
0

You can create the code for this functionality yourself as well:

String output = "";

for (int i = 0; i < listOfStrings.length; i++)
{
    listOfStrings[i] = "\"" + listOfStrings[i] + "\"";
    output += listOfStrings[i] + ", ";
}
bas
  • 1,678
  • 12
  • 23
0
public static void main(String[] args) {
    // TODO code application logic here
    String [] listOfStrings = {"day", "campaign", "imps", "conversions"};
    String output = "";

    for (int i = 0; i < listOfStrings.length; i++) {
        output += "\"" + listOfStrings[i] + "\"";
        if (i != listOfStrings.length - 1) {
            output += ", ";
        }
    }

    System.out.println(output);
}

Output: "day", "campaign", "imps", "conversions"

Sommes
  • 9
  • 2
  • Sommes - StringUtils.join is a much cleaner solution. I wanted to know if any of the libraries have a functionality to append double quotes as well. – Anand Aug 14 '13 at 09:41
0

There is no method present in JDK which can do this, but you can use the Apache Commons Langs StringUtls class , StringUtils.join() it will work

Himanshu Mishra
  • 100
  • 2
  • 10
  • Himanshu - I am already using StringUtils.join. I would like to know how we can append the double quotes to the string. I am sorry for not being clear on that. I will edit my post. – Anand Aug 14 '13 at 09:44
0

A more generic way would be sth. like:

private static class QuoteFunction<F> {
    char quote;

    public QuoteFunction(char quote) {
        super();
        this.quote = quote;
    }

    Function<F, String> func = new Function<F,String>() {
        @Override
        public String apply(F s) {
            return new StringBuilder(s.toString().length()+2).append(quote).append(s).append(quote).toString();
        }
    };

    public Function<F, String> getFunction() {
        return func;
    }
}

... call it via the following function

public static <F> String asString(Iterable<F> lst, String delimiter, Character quote) {
    QuoteFunction<F> quoteFunc = new QuoteFunction<F>(quote);
    Joiner joiner = Joiner.on(delimiter).skipNulls();
    return joiner.join(Iterables.transform(lst, quoteFunc.getFunction()));
}
John Rumpel
  • 4,535
  • 5
  • 34
  • 48