Tuesday, 22 March 2016

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 List and each Person has a firstName 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



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...