Solved

Convert a java arraylist to comma delimited string

Posted on 2008-06-13
4
7,954 Views
Last Modified: 2008-06-13
Is there a fast way to convert a java arraylist to comma delimited string without using an Iterator?
0
Comment
Question by:lasutton
4 Comments
 
LVL 27

Accepted Solution

by:
rrz earned 500 total points
ID: 21779141
You could use
String  listStringWithBrackets = myList.toString();
and then strip the brackets.
0
 

Author Comment

by:lasutton
ID: 21779228
Thanks!

String myString= myArrayList.toString();
myString= myString.substring(1,myString.length()-1);
       
0
 
LVL 9

Expert Comment

by:brunoguimaraes
ID: 21779256
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
 
LVL 23

Expert Comment

by:Ajay-Singh
ID: 21779300
> 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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now