froadie froadie - 1 year ago 57
Java Question

Best way to build a delimited string from a list in java

I have a list of objects, and each object has a string property. For example, I have a

and each
has a
property. I want to build a comma-delimited, quoted string that looks like this:

'James', 'Lily', 'Michael'

Considering that java doesn't seem to have a join method (and besides, this is a bit more complicated than a simple delimited string), what's the most straightforward way to do this? I've been trying to code this for a bit but my code's gotten very messy and I could use some fresh input.

Answer Source

If you want to do it simply and manually, you could do something like this:

String mystr = "";
for(int i = 0; i < personlist.size(); i++) {
  mystr += "\'" + personlist.get(i).firstName + "\'";
  if(i != (personlist.size() - 1)) {
    mystr += ", ";

Now mystr contains your list. Note that the comma is only added if we are not acting on the last element in the list (with index personlist.size() - 1).

Of course, there are more elegant/efficient methods to accomplish this, but this one is, in my opinion, the clearest.