Join multiple Strings in Java using a delimiter

In this post, we will see how to join multiple strings in Java (specified as an array, Iterable, varargs, etc) with a delimiter.


 

1. Using Loop

The idea is to loop through the collection and append each element to String separated by a delimiter. The variable prefix is used to avoid adding delimiter to the end of the output.

 

Download   Run Code

Output:

A,B,C,D

 

2. Java 8 – String.join()

From Java 8 onward, we can use String.join() method which joins strings together with specified separator. This method only works on Iterable and varargs.

 

Download   Run Code

Output:

A,B,C,D

 

3. Guava – Joiner class

Similar to String.join() method, Guava provides Joiner class which joins elements of a collection(Iterable, Iterator, Object[]) with a separator.

 

Download   Run Code

Output:

A,B,C,D

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of