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!
If you use iterator instead of for...each your code could look like this:
Assuming your foreach loop goes through the file in order just add a new line to every string and remove the last new line when your loop exits.
Here's my succinct version, which uses the StringBuilder's length property instead of an extra variable:
(Apologies and thanks to both Jon and Joel for "borrowing" from their examples.)
Ha! Thanks to this post I've found another way to do this:
Of course this is in C# now and Java won't (yet) support the extension method, but you ought to be able to adapt it as needed — the main thing is the use of
String.Join
anyway, and I'm sure java has some analog for that.Also note that this means doing an extra iteration of the strings, because you must first create the array and then iterate over that to build your string. Also, you will create the array, where with some other methods you might be able to get by with an IEnumerable that only holds one string in memory at a time. But I really like the extra clarity.
Of course, given the Extension method capability you could just abstract any of the other code into an extension method as well.
One solution is to create a custom wrapper to StringBuilder. It can't be extended, thus a wrapper is required.
}
Implementation like such:
This does have some downsides:
I went with the StringUtils.join solution for iterating over collections and even building lightweight build method patterns in the code.
This is where a join method, to complement split, would come in handy, because then you could just join all the elements using a new line as the separator, and of course it doesn't append a new line to the end of the result; that's how I do it in various scripting languages (Javascript, PHP, etc.).