Solved

Convert a java arraylist to comma delimited string

Posted on 2008-06-13
4
7,973 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses

636 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