How do I append a newline character for all lines

2019-02-01 05:44发布

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!

15条回答
做个烂人
2楼-- · 2019-02-01 06:05

If you use iterator instead of for...each your code could look like this:

StringBuilder builder = new StringBuilder();

Iterator<Map.Entry<MyClass.Key, String>> it = data.entrySet().iterator();

while (it.hasNext()) {
    Map.Entry<MyClass.Key, String> entry = it.next();

    builder.append(entry.key())
    .append(": ")
    .append(entry.value());

    if (it.hasNext()) {
        builder.append("\n");
    }
}
查看更多
狗以群分
3楼-- · 2019-02-01 06:10

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.

查看更多
太酷不给撩
4楼-- · 2019-02-01 06:12

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.)

查看更多
聊天终结者
5楼-- · 2019-02-01 06:13

Ha! Thanks to this post I've found another way to do this:

public static class Extensions
{
    public static string JoinWith(this IEnumerable<string> strings, string separator)
    {
        return String.Join(separator, strings.ToArray());
    }
}

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.

查看更多
冷血范
6楼-- · 2019-02-01 06:14

One solution is to create a custom wrapper to StringBuilder. It can't be extended, thus a wrapper is required.

public class CustomStringBuilder {

final String separator = System.getProperty("line.separator");

private StringBuilder builder = new StringBuilder();

public CustomStringBuilder appendLine(String str){
    builder.append(str + separator);
    return this;
}

public CustomStringBuilder append(String str){
    builder.append(str);
    return this;
}

public String toString() {
    return this.builder.toString();
}

}

Implementation like such:

CustomStringBuilder builder = new CustomStringBuilder();

//iterate over as needed, but a wrapper to StringBuilder with new line features.

builder.appendLine("data goes here");
return builder.toString();

This does have some downsides:

  • Writing code that's typically not "domain / business" centric
  • Not using open source standard solution like: StringUtils.join
  • Forced to maintain a class that wraps a JDK class that's final and thus updates required long term.

I went with the StringUtils.join solution for iterating over collections and even building lightweight build method patterns in the code.

查看更多
三岁会撩人
7楼-- · 2019-02-01 06:14

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.).

查看更多
登录 后发表回答