Merge elements of a Java Collection separated by a delimiter

Given a Java Collection, construct a new String containing string representation of its elements separated by the specified delimiter.


 

1. Using StringBuilder

The idea here is to iterate through the collection and append each element to a StringBuilder along with the specified delimiter. Finally, return the string representation of the StringBuilder.

 

Download   Run Code

Output:

I-love-Java

 

2. Java 8 – StringJoiner Class

In previous approach, we’re appending the delimiter to StringBuilder for every pair of consecutive elements in the collection. From Java 8 onward, we can use StringJoiner class which takes the separator during initialization itself.

 

Download   Run Code

Output:

I-love-Java

 

3. Guava Joiner

Similar to StringJoiner class, Guava library Joiner class is designed to solve the similar problem. The idea remains the same – create a joiner, and configure the separator and specify the collection to be added.

 

Download   Run Code

Output:

I-love-Java

 

4. Java 8 – String.join()

StringJoiner class provides the flexibility of adding the selected elements from the collection. In case we need to add the whole Collection, we can use static join() method of the String class from Java 8 onward.

 

Download   Run Code

Output:

I-love-Java

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Leave a Reply

Notify of
avatar
wpDiscuz