Link to home
Start Free TrialLog in
Avatar of lasutton
lasutton

asked on

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?
ASKER CERTIFIED SOLUTION
Avatar of rrz
rrz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lasutton
lasutton

ASKER

Thanks!

String myString= myArrayList.toString();
myString= myString.substring(1,myString.length()-1);
       
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

> 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.