This week's book giveaways are in the iOS and Features new in Java 8 forums.
We're giving away four copies each of Barcodes with iOS: Bringing together the digital and physical worlds and Core Java for the Impatient and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes Convert List to comma delimited string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Barcodes with iOS this week in the iOS forum
or Core Java for the Impatient in the Java 8 forum!

JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Convert List to comma delimited string" Watch "Convert List to comma delimited string" New topic

Convert List to comma delimited string

Joe Gliniecki

Joined: Oct 25, 2007
Posts: 18
I'm converting some code to use some of the new features in Java 1.5. The old code looks something like this:

Is there a similar way to do this in a foreach loop? I can't find anything to check whether the current item in the foreach loop is the last one.

The only way I see to do it is either with the Iterator above, or with a foreach and getting rid of the comma at the end of the string after you exit the loop.

I know this isn't an earth shattering question, but curious if I'm missing another way to do this using foreach.

Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 31551

I can think of two ways:
1) Use a boolean to check if you are in the first iteration of the loop.
2) Always add the delimiter and then do a substring at the end to get rid of the last one.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3019
I use something like this:

Rob Spoor

Joined: Oct 27, 2005
Posts: 19897

And Mike's code also included another good advice: use StringBuilder instead of String for all the adding.

Everytime you concatenate Strings using +, a new StringBuilder object will be created. For example, will be turned into By specifically using a StringBuilder, you'll make sure there is only one StringBuilder object instead of one per iteration.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Convert List to comma delimited string