user697911 user697911 - 1 month ago 9
Java Question

Print comma delimited items from a List

List<String> strs = new ArrayList<String>();
strs.add("a");
strs.add("b");
strs.add("c");

for(String str : strs) {
System.out.println(str + ",");
}


This will print as "a, b, c,". I can do a substring() extraction to remove the trailing comma, but it seems awkward. How to avoid the last comma in the iteration?

Answer

Another solution:

String separator = "";
for(String str : strs) {
    System.out.print(separator+str);
    separator = ",";
}