-2

Possible Duplicate:
The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

I have a Collection

I wanted to have a String object from the Collection Object with elements as Comma seperated.

For eg

      Collection<String> = [1,2,3..]
      String temp = "1,2,3,4....";
Community
  • 1
  • 1
Saurabh Kumar
  • 16,353
  • 49
  • 133
  • 212

2 Answers2

1
public static String getCsv(List<String> list) {
    if (list == null)
        return null;
    StringBuilder buff = new StringBuilder();
    for(int i=0; i<list.size(); i++){
          String item = list[i];
          if (i!=0)
              buff.append(",");
          buff.append(item);
    }
    return buff.toString();
 }
Milan Aleksić
  • 1,415
  • 15
  • 33
  • this code should take care properly of first/last element and it is using StringBuilder instead of StringBuffer since it is faster by a small margin in non-concurrent code – Milan Aleksić Aug 08 '11 at 10:42
0

iterate over your collection and use a StringBuilder and append each element and a comma. if the collection has more then 0 elements, delete the last comma.

public static String getMyString(Collection<String> coll) { 
    StringBuilder sb = new StringBuilder();
    for (String str : coll) {
        sb.append(str).append(",");
    }

    if (coll.size() > 0) {
        sb.delete(sb.length()-1,sb.length());
    }
    return sb.toString();
}
amit
  • 175,853
  • 27
  • 231
  • 333