Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

Assume that I have a list of Strings.

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

When I use StringUtils.join(",", s) it gives me the result as

"one, two, three"

Whereas I need the output as

"one","two","three"

We don't like to use Guava utility as the project is not in active state.

Is it possible via Apache Commons utility?

How can I achieve this via utility instead of writing my own logic to do the same?

like image 619
Kathiresa Avatar asked Aug 22 '16 06:08

Kathiresa


People also ask

How do you split a string with double quotes?

split("(? =\"[^\"]. *\")");

How do you print double quotes in conversion string?

The first method to print the double quotes with the string uses an escape sequence, which is a backslash ( \ ) with a character. It is sometimes also called an escape character. Our goal is to insert double quotes at the starting and the ending point of our String.


1 Answers

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
like image 56
akash Avatar answered Oct 01 '22 07:10

akash