How to Create Comma Separated String in Single Quotes from Arraylist of String in Java

JAVA Comma separated string to single quoted string

public static String generateDynamicQueryForInAndValue(String sqlQuery, String stringList, String value1, String value2)
{
StringBuilder listWithBrackets = new StringBuilder();
if(stringList == null || stringList.isEmpty()){
stringList = "''";
}else{

stringList=stringList.replaceAll("^|$", "'").replaceAll(",", "','");
}
listWithBrackets = listWithBrackets.append('(').append(stringList).append(')');
String value1WithQoutes = "'"+value1+"'";
String value2WithQoutes = "'"+value2+"'";
String finalQuery = sqlQuery.replace("@REPLACEMENT-IN@", listWithBrackets);
finalQuery = finalQuery.replace("@REPLACEMENT-1@", value1WithQoutes);
finalQuery = finalQuery.replace("@REPLACEMENT-2@", value2WithQoutes);
return finalQuery;
}

How to add or insert ' (single quotes) for every string in a list in which strings are separated by commas using Java

  1. Iterate the list (for/while).

  2. For each element in the list append <element-of-list>. Hint: use append() on StringBuilder.

  3. Truncate/substring the list to remove the last element added. Hint: use substring on String class.

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

Best way to convert list to comma separated string in java

Since Java 8:

String.join(",", slist);

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here

How do I read strings from a file that already contain double quotes?

Sorry. Actually this is better

add(s.replace("\"", ""));


Related Topics



Leave a reply



Submit