How to add double quotes automatically, converting list of strings as comma separated value

You can do it in two steps with StringUtils only,

List<String> s = new ArrayList<>();
s.add("one");
s.add("two");
s.add("three");

String step1 = StringUtils.join(s, "\", \"");// Join with ", "
String step2 = StringUtils.wrap(step1, "\"");// Wrap step1 with "

System.out.println(step2);

Output,

"one", "two", "three"

BUT

I need to pass them in a mongo DB query when using $in operator

For mongodb query you don't need to build it this way, specifically in case of $in you can query documents in following way,

BasicDBObject yourInQuery = new BasicDBObject();
yourInQuery.put("in_column", new BasicDBObject("$in", yourList));
DBCursor cursor = collection.find(yourInQuery);

Please read more about this in following link,

  • Find or Query Data with Java Driver

String joined = s.stream()
    .map(plain -> '"' + StringEscapeUtils.escapeJava(plain) + '"')
    .collect(Collectors.joining(", "));

The idea is to first convert each of the strings to a properly quoted representation and then join them.

You have to decide for yourself which escaping function to use. And just in case you are generating a CSV file, you should really use some CsvWriter class.

Tags:

Java