Win a copy of Rust Web Development this week in the Other Languages forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Ron McLeod
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Rob Spoor
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Jesse Silverman
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Frits Walraven

Convert List to comma delimited string

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.

Thanks,
Joe
 
author & internet detective
Posts: 40913
840
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Rancher
Posts: 4064
56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I use something like this:


 
Sheriff
Posts: 22567
122
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic