Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.5k points)

When you have to loop through a collection and make a string of each data separated by a delimiter, you always end up with an extra delimiter at the end, e.g.

for (String serverId : serverIds) {

  sb.append(serverId);

   sb.append(",");

}

Gives something like : serverId_1, serverId_2, serverId_3,

I would like to delete the last character in the StringBuilder (without converting it because I still need it after this loop)

1 Answer

0 votes
by (46k points)

Here's a good approach:

String prefix = "";

for (String serverId : serverIds) {

  sb.append(prefix);

  prefix = ",";

  sb.append(serverId);

}

Alternatively, you can try the Joiner class from Guava :)

In Java 8, you will find StringJoiner in the standard JRE.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

Browse Categories

...