Alex Rivera | Logout

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

Asked 2009-01-15T20:24:28.817
33

I'm iterating through a HashMap (see my earlier question for more detail) and building a string consisting of the data contained in the Map. For each item, I will have a new line, but for the very last item, I don't want the new line. How can I achieve this? I was thinking I could so some kind of check to see if the entry is the last one or not, but I'm not sure how to actually do that.

Thanks!

Edit
Report

2 Answers

13

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.

answered 2009-01-16T14:29:34.303
2

Here's my succinct version, which uses the StringBuilder's length property instead of an extra variable:

StringBuilder builder = new StringBuilder();

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

(Apologies and thanks to both Jon and Joel for "borrowing" from their examples.)

answered 2009-01-16T14:15:48.930

Your Answer