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
Print the first word on its own if it exists. Then print the pattern as comma first, then the next element.
With a
List
, you're better off using anIterator
The output: The result is: Aplha, Beta, Gamma
You could use a standard function in the java.util package and remove the block quotes at start and end.
I would write it this way:
If arrayListWords has two words, it should print out A,B
You can use an
Iterator
on theList
to check whether there are more elements.You can then append the comma only if the current element is not the last element.
However it is much easier to use a 3rd party library like Guava to do this for you. The code then becomes:
With Java 8 it got much easier, no need for 3rd parties -