How do I append a newline character for all lines except the last one?

What about this?

StringBuilder result = new StringBuilder();

for(Map.Entry<MyClass.Key,String> entry : data.entrySet())
{
    builder.append(entry.key())
       .append(": ")
       .append(entry.value())
       .append("\n");
}

return builder.substring(0, builder.length()-1);

Obligatory apologies and thanks to both Jon and Joel for "borrowing" from their examples.


one method (with apologies to Jon Skeet for borrowing part of his Java code):

StringBuilder result = new StringBuilder();

string newline = "";  
for (Map.Entry<MyClass.Key,String> entry : data.entrySet())
{
    result.append(newline)
       .append(entry.key())
       .append(": ")
       .append(entry.value());

    newline = "\n";
}

Ususally for these kind of things I use apache-commons-lang StringUtils#join. While it's not really hard to write all these kinds of utility functionality, it's always better to reuse existing proven libraries. Apache-commons is full of useful stuff like that!


Change your thought process from "append a line break all but the last time" to "prepend a line break all but the first time":

boolean first = true;
StringBuilder builder = new StringBuilder();

for (Map.Entry<MyClass.Key,String> entry : data.entrySet()) {
    if (first) {
        first = false;
    } else {
        builder.append("\n"); // Or whatever break you want
    }
    builder.append(entry.key())
           .append(": ")
           .append(entry.value());
}