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();
}
精彩评论