Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 7988
  • Last Modified:

Convert a java arraylist to comma delimited string

Is there a fast way to convert a java arraylist to comma delimited string without using an Iterator?
0
lasutton
Asked:
lasutton
1 Solution
 
rrzCommented:
You could use
String  listStringWithBrackets = myList.toString();
and then strip the brackets.
0
 
lasuttonAuthor Commented:
Thanks!

String myString= myArrayList.toString();
myString= myString.substring(1,myString.length()-1);
       
0
 
brunoguimaraesCommented:
Actually the toString method will not return the arraylist's values, unless you override it.

I think you'll have to iterate through the arraylist, but you can use the enhanced for loop (if you're using JDK 5 or greater):
StringBuilder sb = new StringBuilder();
int count = 0;
 
for (String s : yourArray) {
     sb.append(s);
     if (++count != yourArray.length) {
         sb.append(",");
     }
}
 
return sb.toString();

Open in new window

0
 
Ajay-SinghCommented:
> Is there a fast way to convert a java arraylist to comma delimited string without using an Iterator?
NO. You need to traverse through the list once to produce the string output. toString method does the same.
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now