B. S. Rawat
B. S. Rawat

Reputation: 1914

How to get data from Set in one go

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.

Upvotes: 0

Views: 3560

Answers (4)

A_M
A_M

Reputation: 7851

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, ','));

Upvotes: 0

Moss Collum
Moss Collum

Reputation: 3582

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"

Upvotes: 3

geofftnz
geofftnz

Reputation: 10102

Assuming C# 3.5

var fruits = new HashSet<string>();

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

Console.WriteLine(string.Join(", ",fruits.ToArray()));

Upvotes: 1

MartinodF
MartinodF

Reputation: 8254

Quick and dirty:

value.toString().substring(1, value.toString().length - 1);

Upvotes: 1

Related Questions