Wednesday, May 11, 2011

Tricky way to convert an array list into a comma separated string

Today my husband suggested me a good way to convert an array list into string, i found it very efficient so sharing with you all.

Created a list l, added megha, dwivedi and jain into it. Need to store - megha, dwivedi, jain into a string so used toString() method.

List l = new ArrayList();
String s = l.toString().substring(1, l.toString().length()-1);

If we perform toString on the list the output will be -

[megha, dwivedi, jain]

but i dont need square brackets so used substring method to cut 1st and last character, so variable 's' will contain - megha, dwivedi, jain

Other inefficient way which comes first in our mind is to iterate through list, get string one by one and append it comma separated, but using the above mentioned way we can avoid all those unnecessary loops and variables.

Thanks to my husband for explaining the same ;)

1 comment:

  1. I seen your blog using google and I must say, this is probably one of the best well prepared articles I have come across in a long time. I have bookmarked your site for more posts.
    recover deleted emails outlook 2007