Sometimes it's hard to tell, ahead of time, when an element you're looking at in an iterator is the last one. In cases like this, it often works best to append the comma before each element instead of after, except for the first element. Thus:
String str = "[";
boolean first = true;
for (double d : data) {
if (!first) {
str += ", ";
}
str += d;
first = false;
}
str += "]";
Another possibility is to use the logic you have now but use substring
or replace
or some other method to remove the extra two characters, like
str = str.replaceFirst(", $", "]");
which uses a regular expression to replace ", "
that appears at the end of the string with a right bracket.