How to join two Optional<String> with a delimiter in Java 8 : <p>I have two <code>Optional</code> strings, <code>name1</code> and <code>name2</code>. I want to join the two such that the result is also an Optional with:</p>

<ol>
<li>If either one is non-empty, the result should be the non-empty name.</li>
<li>If both are non-empty, I want the result to be joined with the delimiter <code>AND</code>.</li>
<li>If both are empty, the result should be an empty <code>Optional</code></li>
</ol>

<p>My attempt at this:</p>

<pre><code>StringBuilder sb = new StringBuilder();
name1.ifPresent(sb::append);
name2.ifPresent(s -&gt; {
    if (sb.length() &gt; 0) {
        sb.append(" AND ");
    }
    sb.append(s);
}
Optional&lt;String&gt; joinedOpt = Optional.ofNullable(Strings.emptyToNull(sb.toString()));
</code></pre>

<p>This works, but seems ugly and not very functional.</p>

<p>PS: There is a similar <a href="https://stackoverflow.com/a/46473336/1314028">question</a> but the accepted answer is wrong. Specifically, if <code>name1</code> is empty and <code>name2</code> is not, it returns an empty optional.</p>
