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

 
1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of