Add a newline to a String if not empty in Java This should be really simple. I'm searching for the cleanest &amp; shortest way to add a newline to a non-null String if it is not empty, i.e. myString.isEmpty() is true. I know of a number of ways to do this, but none of them are as elegant as I would like them to.

For context, the string I'm working on will essentially be a list of key-value pairs that is filled with a loop. Every key-value-pair needs to have a newline appended after it, though not if it is the last one. An example for the end value of myString might be the following:

Boss : Julia
Worker : Louis
Intern : Tom


I could do

myString += myString.isEmpty() ? "" : "\n";


but is this really the best way to do this?

I also thought of 

if(!myString.isEmpty()) myString += "\n";


Which way would be preferable, and why?
Are there better alternatives?
Every key-value-pair needs to have a newline appended after it, though not if it is the last one.


So are you interested to know how to concatenate Strings together using \n as a delimiter, or are you still interested to know how can you append \n to a non-empty String? Both have different implementations...

(using Java 8 where applicable below)

\n as a delimiter:

String toString = organizationMap.entrySet().stream()
                    .map(ThisClass::constructStringFromEntry)
                    .filter(v -&gt; !v.isEmpty())
                    .collect(Collectors.joining("\n"));


\n as an optional suffix:

StringBuilder builder = new StringBuilder();
Iterator&lt;Entry&lt;String, String&gt;&gt; iterator = organizationMap.entrySet().iterator();
while (iterator.hasNext()) {
    Entry&lt;String, String&gt; entry = iterator.next();
    // some other processing...
    // time to append the current entry to builder
    String entryString = constructStringFromEntry(entry);
    builder.append(entryString);
    if (!entryString.isEmpty() &amp;&amp; iterator.hasNext()) {
        builder.append('\n');
    }
}
String toString = builder.toString();


I am suggesting the usage of a StringBuilder here since the kind of String concatenation in a loop is usually structured, hence it can be better done relying on that rather than +. Usually, I will prefer the enhanced for-loop over using an explicit Iterator, but its usage here is required in order to avoid adding the last \n.