This post will discuss how to print elements of a List separated by a comma in Java.

1. Using StringJoiner class

Since Java 8, you can use the StringJoiner class to construct a sequence of elements separated by a delimiter and optionally starting with a prefix and ending with a suffix.

Download  Run Code

Output:

Java, C++, Ruby, JavaScript

 
For a List<Integer>, you can call Objects.toString() or String.valueOf() method before adding it to the StringBuilder instance.

Download  Run Code

Output:

1, 2, 3, 4, 5

 
Here’s another version that creates a string starting with the supplied prefix and ending with the supplied suffix.

Download  Run Code

Output:

[Java, C++, Ruby, JavaScript]

2. Using Stream API

Another alternative in Java 8 and above is using the Collectors.joining() collector that concatenates the stream elements, separated by the specified delimiter.

Download  Run Code

Output:

Java, C++, Ruby, JavaScript

 
The joining collector is overloaded to accept the prefix and suffix as well.

Download  Run Code

Output:

[Java, C++, Ruby, JavaScript]

3. Using String.join() method

If you have a List of strings, you directly call the String.join() method. It returns a new string composed of all elements of the specified iterable joined together with the specified delimiter. The method is also available since JDK 1.8.

Download  Run Code

Output:

Java, C++, Ruby, JavaScript

4. Using Guava

Similar to the String.join() method, Guava offers a Joiner class, to concatenate elements of a list using a provided delimiter.

Download Code

Output:

Java, C++, Ruby, JavaScript

 
All other solutions add null to the final sequence if any of the list elements is null. However, Guava’s join() method will throw NullPointerException if an individual element is null. The Joiner class provides flexibility to skip over the null elements using the skipNulls() method. Its usage is demonstrated below:

Download Code

Output:

C, C++, Java

5. Using Apache Commons Lang

Apache Commons Lang library StringUtils class offers the join() method that joins elements of a list into a single string, separated by the supplied delimiter. Any null elements in the list are mapped to an empty string before joining.

Download Code

Output:

Java, C++, Ruby, JavaScript

6. Using Custom Routine

If you don’t use Apache Commons or Guava third-party libraries in your project and on earlier versions of Java (Java 7 and earlier), you can implement your custom logic as shown below.

Download  Run Code

Output:

Java, C++, Ruby, JavaScript

That’s all about printing elements of a List separated by a comma in Java.