0

For Example a set{1,2,3,4,5} with a delimiter @ I want to have a return string of 1@2@3@4@5

The tricky part is, I have many different sets,

Set<Integer>, Set<String>, Set<Long> and so on. 

And I know I can do it in separate functions using a loop. But I just don't want to be tedious and want to do it in one function using Java Generics or whatever that can help. I have done some brain storm but in vain. :(

Any idea is appreciated!

roland luo
  • 1,561
  • 4
  • 19
  • 24

3 Answers3

2

You can use the join method of StringUtils class of the Commons Lang library

Example:

Set<Integer> theSet = new HashSet<Integer>();
theSet.add(1);
theSet.add(2);
theSet.add(3);
theSet.add(4);
theSet.add(5);
System.out.println(StringUtils.join(theSet,'@'));

Output: 1@2@3@4@5

M. Abbas
  • 6,409
  • 4
  • 33
  • 46
0

Edit: the answer from mabbas is a better idea than this.

It's not particularly great, but will work assuming that your Set contains objects whose toString representations you want to concatenate

public String concatenateSet(Set<?> set) {
    return set.stream()
            .map(Object::toString)
            .reduce((previous, current) -> previous + "@" + current)
            .orElse("");
}

Step by step:

Calling stream() gets you a stream of items in the set

Calling map(Object::toString) calls toString on each item of the set

Calling reduce((previous, current) -> previous + "@" + current) concatenates the toString representations of each object with @ as a delimiter between each item

Calling orElse("") will ensure that an empty sting is returned if, for example, the set is empty

Community
  • 1
  • 1
beresfordt
  • 5,088
  • 10
  • 35
  • 43
0

You're over thinking it. You can just take a Set as a parameter and it will cover every type of set. Just make sure your objects implement toString().

public static String setToString(Set set)
{
    Iterator it = set.iterator();
    StringBuffer out = new StringBuffer(it.next().toString());
    while (it.hasNext())
    {
        out.append("@" + it.next());
    }
    return out.toString();
}
Amber
  • 2,413
  • 1
  • 15
  • 20
  • I think op is looking for a String to be returned by the function, rather than sysout of the concatenated Set – beresfordt Feb 18 '15 at 21:49
  • 1
    It's the same idea either way. They just need one function that will handle sets of any type of object. Technically you are correct though... Fixed it. – Amber Feb 18 '15 at 21:52