Search code examples
javajava-streamstringbuilder

How to get rid of trailing comma and space in the end of the stringBuilder?


I added a comma when it is missing in the string and want to get rid of the comma from the end of the string and trim additional space from the new line in the end.

StringBuilder mssg = new StringBuilder();

if (hasError().size <=8){
hasError().keySet().stream().forEach(id ->{
mssg.append(id.toString() + ":");
hasError().get(id).stream.limit(8).forEach(error ->mssg.append(error.toString() + ", "))
mssg.append("\n"); // adding new line for each Id to show it's own error mssg
)}


error output: Missing xnameMissing ynameMissing xyzMissing abcMissing ab, cd or ef,
Id: Id1

so with my code - I am adding comma separating the error output to the string so the output of mssg would be

mssg output: Id1: Missing xname, Missing yname, Missing xyz, Missing abc, Missing ab, cd, or ef,

there is multiple missing error output for 1 item

Id1:Missing xname, Missing yname, Missing xyz, Missing abc, Missing ab, cd, or ef,
Id2:Missing yname, Missing ab, cd, or ef,
Id3:Missing xyz,
new line 

Solution

  • If you simply want to remove the last 2 characters from a StringBuilder:

    sb.setLength(sb.length() - 2);
    

    To cater for the case where the original list could be empty:

    sb.setLength(Math.max(0, sb.length() - 2));
    

    But I think a better solution would be to not put the misplaced separator there in the first place; e.g. build the string like this:

    stream.limit(8).map(Object::toString).collect(Collectors.joining(", "))