Print out elements from an array with a comma between elements except the last word
I am printing out elements from an array list and want to have a comma between each word except the last word. Right now I am doing it 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!
Print the first word on its own if it exists. Then print the pattern as comma first, then the next element.
if (arrayListWords.length >= 1) {
System.out.print(arrayListWords[0]);
}
// note that i starts at 1, since we already printed the element at index 0
for (int i = 1; i < arrayListWords.length, i++) {
System.out.print(", " + arrayListWords[i]);
}
With a List
, you're better off using an Iterator
// assume String
Iterator<String> it = arrayListWords.iterator();
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", " + it.next());
}
I would write it this way:
String separator = ""; // separator here is your ","
for (String s : arrayListWords) {
System.out.print(separator + s);
separator = ",";
}
If arrayListWords has two words, it should print out A,B
Using Java 8 Streams:
Stream.of(arrayListWords).collect(Collectors.joining(", "));
StringJoiner str = new StringJoiner(", ");
str.add("Aplha").add("Beta").add("Gamma");
String result = str.toString();
System.out.println("The result is: " + result);
The output: The result is: Aplha, Beta, Gamma
While iterating, you can append the String s
to the StringBuilder
and at the end, you can delete the last 2 chars which is an extra ,
and a space (res.length() -2
)
StringBuilder res = new StringBuilder();
for (String s : arrayListWords) {
res.append(s).append(", ");
}
System.out.println(res.deleteCharAt(res.length()-2).toString());