I am printing out elements from a array list, I want to have a comma between each word except the last word. Right now I am doing like this:
for (String s : arrayListWords) {
System.out.print(s + ", ");
}
As you understand it will print out the words like this: "one, two, three, four," and the problem is the last comma, how do I solve this? All answers appreciated!
Best regards, Erica
Here is what I come up with:
off course we can utalise
StringBuilder
but of all solutions, I like@Mav
answer as it's more efficient and clean.Just use the toString() method.
Using Java 8 Streams:
While iterating, you can append the
String s
to theStringBuilder
and at the end, you can delete the last 2 chars which is an extra,
and a space (res.length() -2
)You can try this
This might be the most efficient means of comma-delimited string using best practices and no "if" checks, no unfamiliar libraries, and
StringBuilder
which is best practice for concatenating strings.Also having a "size" variable reduces the calls to the
.size()
method.For those using
String[]
:For those using
ArrayList<String>
:Both yield:
one,two,three,four