开发者

Convert a Collection<String> into comma sepearted values [duplicate]

开发者 https://www.devze.com 2023-03-26 09:33 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: The most sophisticated way for creating comma-separated Strings开发者_StackOverflow社区 from a Collection/Array
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

The most sophisticated way for creating comma-separated Strings开发者_StackOverflow社区 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....";


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();
 }


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();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消