Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

Tags:

java

string

sql

During my work with databases I noticed that I write query strings and in this strings I have to put several restrictions in the where-clause from a list/array/collection. Should look like this:

select * from customer  where customer.id in (34, 26, ..., 2); 

You can simplify this by reducing this to the question that you have collection of strings and want to create a comma-separated list of this strings in just one string.

My approach I have used so far is something like that:

String result = ""; boolean first = true; for(String string : collectionOfStrings) {     if(first) {         result+=string;         first=false;     } else {         result+=","+string;     } } 

But this is as you can see very ugly. You cannot see what happens there on the first look, especially when the constructed strings (like every SQL query) is getting complicated.

What is your (more) elegant way?

like image 467
maerch Avatar asked Oct 15 '08 17:10

maerch


People also ask

How do you make a comma-separated string from an array?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do you add comma-separated Values in an ArrayList?

All you need to do is first split the given String on delimiter e.g. comma using the split() method, this will give you an array of String. Now, you can pass that array to Arrays. asList() method to create a list, but remember this would be a fixed-length list and not truly an ArrayList.

How do you split comma-separated values in an array?

Use the String. split() method to convert a comma separated string to an array, e.g. const arr = str. split(',') . The split() method will split the string on each occurrence of a comma and will return an array containing the results.

How do you get a comma-separated string from an array in C?

How to get a comma separated string from an array in C#? We can get a comma-separated string from an array using String. Join() method. In the same way, we can get a comma-separated string from the integer array.


1 Answers

Use the Google Guava API's join method:

Joiner.on(",").join(collectionOfStrings); 
like image 191
Julie Avatar answered Sep 17 '22 12:09

Julie