views:

176

answers:

4

I want to get all values of a set interface in one go as a comma separated string.

For Example(Java Language):

Set<String> fruits=  new HashSet<String>();

fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");

If I print the set as fruits.toString then the output would be:

[Apple, Banana, Orange]

But my requirement is Apple, Banana, Orange without the square brackets.

Please suggest.

+1  A: 

Quick and dirty:

value.toString().substring(1, value.toString().length - 1);
MartinodF
Thanks for your answer :)
Garhwali Bhai
Yeah, I can't see any reason this would fail. It would be much cleaner to iterate through the set, creating the string as you go, but this is good enough.
ChristianLinnell
At least don't call toString twice.
Matthew Flaschen
I don't even know which language is that!
MartinodF
This is from Java Language
Garhwali Bhai
+1  A: 

Assuming C# 3.5

var fruits = new HashSet<string>();

fruits.Add("Apple");
fruits.Add("Banana");
fruits.Add("Orange");

Console.WriteLine(string.Join(", ",fruits.ToArray()));
geofftnz
+3  A: 

I'm assuming this is Java.

MartinodF's quick and dirty toString().substring approach will work, but what you're really looking for is a join method. If you do a lot of string manipulation, I'd suggest you take a look at the Apache Commons Lang library. It provides a lot of useful features that are missing from the Java standard library, including a StringUtils class that would let you do this:

Set fruits =  new HashSet();

fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");

String allFruits = StringUtils.join(fruits, ", ");
// allFruits is now "Apple, Banana, Orange"
Moss Collum
Not bad idea, but for above code I have to used commons-lang.jar file which is not acceptable in my case.
Garhwali Bhai
why is this not acceptable?
Salandur
Because it's homework and he should have to figure it out himself?
Omar Kooheji
I am a developer in my team therefore I can’t ask architecture team to use a new jar file for only these kinds of transformation. So finally I have made a generic method which will convert collection data to comma separated string, I asked this question because I thought some intelligent guys know some better and optimized solution.
Garhwali Bhai
Here is developed code:private String collectionToCommaSeparatedString(Collection<String> value){ Iterator<String> it = value.iterator(); StringBuilder result = new StringBuilder(); while ( it.hasNext() == true ) { result.append( it.next()); if(it.hasNext()) result.append(","); } return result.toString() ; }
Garhwali Bhai
A: 

Use StringUtils.join from commons lang

Set fruits =  new HashSet();

fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");


System.out.println(StringUtils.join(fruits, ','));
A_M