Remove extra delimiter at the end of StringBuilder in Java

In this post, we will see how to remove extra delimiter at the end of a Stringbuilder which gets added while looping through a Collection and appending each element to Stringbuilder separated by a delimiter.


 
For instance, consider below code that will add an extra delimiter at the end.

 

Download   Run Code

 

This is a very common problem which every Java developer must have faced at-least once in his lifetime. Lets discuss few methods to fix above problem:

 

1. For Loop

This method still loop through the collection but does that in a clever way. Instead of appending the delimiter, it appends the delimiter at the starting of each value, and use empty string as delimiter for the first value of the collection.

 

Download   Run Code

Output:

BLUE,RED,GREEN

 

2. Use a Variable

The idea is to maintain a variable that holds the collection size and add delimiter only if we’re not at the last element in the list.

 

Download   Run Code

Output:

BLUE,RED,GREEN

 

3. StringJoiner Class

In Java 8 and above, we can use StringJoiner class in place of StringBuilder, which takes a delimiter and construct a sequence of values separated by the delimiter.

 

Download   Run Code

Output:

BLUE,RED,GREEN

 

4. Naive method

Below solutions allows the loop to add the extra character at the end of StringBuilder but removes it using utility methods provided by String/StringBuilder class:

 

4.1. Using substring() method

 

Download   Run Code

Output:

BLUE,RED,GREEN

 

4.2. Using setLength() method

 

Download   Run Code

Output:

BLUE,RED,GREEN

 

4.3. Using deleteCharAt() method

 

Download   Run Code

Output:

BLUE,RED,GREEN

 

 
Related Post: Delete extra separator from end of the String

 
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 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of