This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Soft Skills and have John Sonmez on-line!
See this thread for details.
The moose likes Java in General and the fly likes Java equivalent for Perl's join ? ( concat Collection w/separator ) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java equivalent for Perl Watch "Java equivalent for Perl New topic
Author

Java equivalent for Perl's join ? ( concat Collection w/separator )

Ken Pelletier
Ranch Hand

Joined: Aug 01, 2002
Posts: 54
I often find myself having to concatenate the string values of objects in a collection into a comma-separated string.
I use a StringBuffer and append() in an iteration over the collection, but I have a nagging feeling that there's a built-in operation for this that I'm just not finding.
Is there a way to concatenate a collection of objects' string values into a string, optionally separated by another character(s) a la Perl's join( separator, array ) ?
I'd expect it to be in the Collections framework, but, apart from AbstractCollection's toString() method - which is close - I can't seem to locate it.
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1824

There's nothing like this that I am aware of. Of course, you could write a function in a helper class to do this for you.

...but I'm sure you could've done that; I just like typing....


Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Ken Pelletier
Ranch Hand

Joined: Aug 01, 2002
Posts: 54
Thanks.
Yeah, that's pretty much exactly what I was referring to when I said:
>I use a StringBuffer and append() in an iteration over the collection
So, I take it there *is* no such animal hidden somewhere in the class libraries.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
I never found one. I have a pair of functions that I write in every new language I play with:
ArrayToString - turns an array into a delimited string. It picks a delimiter that is not in any of the strings in the array and uses it as the FIRST character of the string. This is not normal.
StringToArray - using the first character as the delimiter (that's why he put it there!) parses the string back into an array.
Because of the delimiter selection logic, you can nest these things until you run out of delimiters.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java equivalent for Perl's join ? ( concat Collection w/separator )